我注意到,如果我使用Write-Error,在使用exit 123之后,$lastexitcode变量没有改变,相反,它仍然包含前面命令中的退出代码。
如果我有这些文件:
test-out.ps1
Write-Output "hello"
exit 3test-err.ps1
Write-Error "hello"
exit 123然后我调用了一个powershell:
.\test-out.ps1
// displays: hello
$lastexitcode
// displays: 3
.\test-err.ps1
// displays: Write-Error: hello
$lastexitcode
// also/still displays: 3我期望$lastexitcode在.\test-err.ps1之后成为123。
我的解决办法是使用[Console]::Error.WriteLine("hello"),但是似乎写错误应该是最好的方法。
文档说
若要写入非终止错误,请输入错误消息字符串、ErrorRecord对象或异常对象。使用写错误的其他参数填充错误记录。
它没有提到它将阻止设置自定义退出代码。更糟糕的是,使用它根本不会设置退出代码。如果以前是0,那么在使用Write-Error之后,exit 1甚至不能工作。
我是不是遗漏了什么?
发布于 2022-08-13 13:08:14
你的症状意味着:
exit 123语句从未被执行Write-Error在默认情况下发出一个非终止错误,碰巧发出一个脚本终止错误,$ErrorActionPreference = 'Stop'是有效的。https://stackoverflow.com/questions/73344421
复制相似问题