【问题标题】:powershell invoke-command does not process try-cache blockpowershell 调用命令不处理 try-cache 块
【发布时间】:2019-03-19 10:01:00
【问题描述】:

我有以下代码:

$output = foreach ($comp in $maschines.name) {
    invoke-command -computer comp1 -ScriptBlock {
        try
        {
            get-vm –VMName $using:comp | Select-Object VMId | Get-VHD | Select-Object @{ label = "vm"; expression = {$using:comp} }, 
            path,
            VhdType, 
            VhdFormat, 
            @{label = "file(gb)"; expression = {($_.FileSize / 1GB) -as [int]} }, 
            @{label = "size(gb)"; expression = {($_.Size / 1GB) -as [int]} }
        }
        catch
        {
            Write-Host some error
        }
    }
}

我不明白

一些错误

但是:

> The operation failed because the file was not found.
>     + CategoryInfo          : ObjectNotFound: (Microsoft.Hyper...l.VMStorageTask:VMStorageTask) [Ge     t-VHD],
> VirtualizationOperationFailedException
>     + FullyQualifiedErrorId : ObjectNotFound,Microsoft.Vhd.PowerShell.GetVhdCommand
>     + PSComputerName        : comp1

我怎样才能得到

一些错误

在缓存块中?

【问题讨论】:

    标签: powershell try-catch invoke-command


    【解决方案1】:

    为了触发 catch 块,需要终止异常(PowerShell 有终止和非终止错误)。

    要强制终止 cmdlet 的错误,您可以使用 -ErrorAction 参数和 Stop 作为值:

    $output = foreach ($comp in $maschines.name) {
        invoke-command -computer comp1 -ScriptBlock {
            try
            {
                get-vm –VMName $using:comp -ErrorAction Stop | Select-Object VMId | Get-VHD | Select-Object @{ label = "vm"; expression = {$using:comp} }, 
                path,
                VhdType, 
                VhdFormat, 
                @{label = "file(gb)"; expression = {($_.FileSize / 1GB) -as [int]} }, 
                @{label = "size(gb)"; expression = {($_.Size / 1GB) -as [int]} }
            }
            catch
            {
                Write-Host some error
            }
        }
    }
    

    【讨论】:

    • 我改成了...get-vm –VMName $using:comp | Select-Object VMId | Get-VHD -ErrorAction Stop | Select-Object @{ label...,它可以工作了。谢谢!
    • 啊,是的,没有注意到 cmdlet 也被使用了。您还可以考虑在脚本的开头使用$ErrorActionPreference = 'Stop' 来强制终止所有 cmdlet 的错误。
    • 我在 catch 中更改了 Write-Host $_.Exception.Message ,错误提示为 The operation failed because the file was not found. 我如何查看哪个文件?
    • 试试Write-Host $_,看看完整的错误记录是否包含您需要的信息。
    • 不,只有The operation failed because the file was not found
    【解决方案2】:

    -ErrorAction Stop 添加到Get-Vm 以使其终止。

    您可以在此处阅读有关在 powershell 中终止非终止 cmdlet 的更多信息:

    https://devblogs.microsoft.com/scripting/understanding-non-terminating-errors-in-powershell/

    https://devblogs.microsoft.com/powershell/erroraction-and-errorvariable/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-31
      • 2019-11-15
      • 1970-01-01
      • 1970-01-01
      • 2015-12-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多