我有以下代码:
$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
我怎样才能得到
一些错误
在cach区块?
为了触发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/