powershell invoke-command 不处理 try-cache 块

powershell invoke-command does not process try-cache block

我有以下代码:

$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
        }
    }
}

我不明白

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

我怎样才能得到

some error

在 catch 块中?

为了触发 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
        }
    }
}

-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/