[英]Dot-sourcing PowerShell script file and return code
Here's some PowerShell code: 这是一些PowerShell代码:
test.ps1: test.ps1:
. C:\path\to\test2.ps1
exit 5
test2.ps1: test2.ps1:
exit 7
Run test.ps1 from a standard command prompt however you like to run PowerShell scripts, then call: 从标准命令提示符运行test.ps1,但是要运行PowerShell脚本,然后调用:
echo %errorlevel%
The expected result is a return code of 7. This is the first exit
command in the PowerShell script. 预期的结果是返回码为7.这是PowerShell脚本中的第一个
exit
命令。 The actual result, however, is a return code of 5. Obviously the included script was terminated but its return code was ignored and the calling script happily continued. 然而,实际的结果是返回码为5.显然,包含的脚本已被终止,但其返回代码被忽略,并且调用脚本继续愉快。
How can I really terminate a script and return a result code no matter how it was called? 我怎样才能真正终止脚本并返回结果代码,无论它是如何被调用的?
Or alternatively, how should I call test2.ps1 so that its return code is passed on to the outside world? 或者,我应该如何调用test2.ps1以便将其返回代码传递给外部世界?
Background: My build script is made with PowerShell and it includes module files for different tasks. 背景:我的构建脚本是使用PowerShell制作的,它包含用于不同任务的模块文件。 One task currently fails and the build server didn't detect the error because my start build script still returned 0.
一个任务当前失败,构建服务器未检测到错误,因为我的启动构建脚本仍返回0。
You should query $lastExitCode
that would have nonzero value if the last script/program exited with failure. 如果最后一个脚本/程序退出失败,您应该查询
$lastExitCode
,该值将具有非零值。 So, your sample's test1.ps1
should be like this: 所以,你的样本的
test1.ps1
应该是这样的:
. C:\path\to\test2.ps1
if ($lastexitcode -ne 0) { exit $lastexitcode}
exit 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.