Powershell invoke-command不处理try-cache块

时间:2019-03-19 10:01:00

标签: powershell try-catch invoke-command

我有以下代码:

$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

我如何获得

  

一些错误

在教练区吗?

2 个答案:

答案 0 :(得分: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
        }
    }
}

答案 1 :(得分:1)

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

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

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

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