gpt4 book ai didi

powershell - Powershell invoke-command不处理try-cache block

转载 作者:行者123 更新时间:2023-12-02 23:35:50 24 4
gpt4 key购买 nike

我有以下代码:

$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块,需要终止异常(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
}
}
}

关于powershell - Powershell invoke-command不处理try-cache block ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55238212/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com