我正在尝试在 PowerShell ISE 中调试脚本,但遇到问题,其中一行的正常输出被 ISE 解释为错误
我已经能够简化此问题的重现: 我在 https://www.openssl.org/related/binaries.html 获取任何版本的 openssl (我使用链接存储库 http://slproweb.com/products/Win32OpenSSL.html 中的 1.0.2d x86 对此进行了测试)
我打开 Powershell ISE,导航到 exe 所在位置并运行以下命令:
$ErrorActionPreference = "Stop"
$env:OPENSSL_CONF = ((Resolve-Path "openssl.cfg").Path)
&openssl.exe genrsa
输出为红色,开始如下:
openssl.exe : Loading 'screen' into random state - done
At line:1 char:1
+ &C:\Trayport\OpenSsl\openssl.exe genrsa
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (Loading 'screen...om state - done:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
Generating RSA private key, 2048 bit long modulus
如果我在普通的 PowerShell 命令窗口中运行此命令,输出是相同的,但为白色,不会被视为错误
Loading 'screen' into random state - done
Generating RSA private key, 2048 bit long modulus
我尝试使用 2>&1 或使用 ErrorPreference 参数封装调用(如 PowerShell ISE throws an error on git checkout 中的建议),但它仍然失败
尝试/捕获所有异常确实有效,但如果可以避免它,我宁愿不这样做。
我尝试过使用 PowerShell 版本 3.0 和 4.0
编辑:如果您使用$ErrorActionPreference = "SilentlyContinue"
,它确实会消除错误,但随后您将无法访问输出,而且合法问题也会消失
最佳答案
Powershell 将任何到错误 channel 的转储解释为应用程序端发生的错误,因此它会停止该点之后的脚本。您应该在调用 openssl.exe
的行中添加 2>&1
,以便 Powershell 不会捕获应用程序的标准错误并将其解释为实际错误。
$ErrorActionPreference = "Stop"
$env:OPENSSL_CONF = ((Resolve-Path "openssl.cfg").Path)
& openssl.exe genrsa 2>&1
更新:这是无法治愈的,Powershell ISE 确实会将标准错误 channel 拦截到 Write-Error
中并触发停止。有一个解决方法here其中包括将生成错误 channel 输出的外部应用包装到本地覆盖 $ErrorActionPreference
的脚本 block 中,如下所示:
& {
$ErrorActionPreference='silentlycontinue'
openssl.exe genrsa 2>&1
}
关于Powershell ISE 错误地将 openssl.exe 正常输出解释为错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31449220/