Powershell相当于Perl的$ CHILD_ERROR

问题描述 投票:-1回答:1

我基本上需要Powershell中执行给定字符串的功能(它可以是CMD / Powershell命令,带参数的perl / python / powershell或带参数的exe等)捕获其退出值。在perl中,我将字符串传递给'system()'并使用'$ CHILD_ERROR'perlval并将其移位以访问退出代码。

在powershell中我无能为力。

我尝试使用Invoke-Expression,但即使传递给Invoke-Expression的表达式失败,Invoke-Expression调用本身也会成功。

windows powershell perl exit exit-code
1个回答
2
投票

您可以使用$ LASTEXITCODE从外部程序或布尔值$?获取退出代码。检查上一次操作是成功还是失败。从PowerShell控制台运行Get-Help about_Automatic_Variables -ShowWindow以查看更多详细信息。

在运行外部程序时,您可能需要检查&(call)命令作为Invoke-Expression的替代方法。有关详细信息,请从PowerShell控制台运行Get-Help about_Automatic_Variables -ShowWindow。

还记得你可以在不使用上述命令之一的情况下调用外部程序。请参阅以下示例:

param($Hostname="127.0.0.1", $Tries=1, $Wait=1000)
$output = ping.exe $Hostname -n $Tries -w $Wait # captures anything written to stdout
$output|? {$_ -match 'Request timed out'}|Write-Warning
$LASTEXITCODE # returns the exit code from ping.exe

您可以将其复制到test.ps1文件并从PowerShell控制台窗口(例如。\ test.ps1 8.8.8.8)运行它以查看它是如何工作的。

© www.soinside.com 2019 - 2024. All rights reserved.