Dot-source PowerShell脚本文件和返回代码

ygo*_*goe 6 powershell

这是一些PowerShell代码:

test.ps1:

. C:\path\to\test2.ps1
exit 5
Run Code Online (Sandbox Code Playgroud)

test2.ps1:

exit 7
Run Code Online (Sandbox Code Playgroud)

从标准命令提示符运行test.ps1,但是要运行PowerShell脚本,然后调用:

echo %errorlevel%
Run Code Online (Sandbox Code Playgroud)

预期的结果是返回码为7.这是exitPowerShell脚本中的第一个命令.然而,实际结果是返回码为5.显然,包含的脚本已被终止,但其返回代码被忽略,并且调用脚本继续愉快.

我怎样才能真正终止脚本并返回结果代码,无论它是如何被调用的?

或者,我应该如何调用test2.ps1以便将其返回代码传递给外部世界?

背景:我的构建脚本是使用PowerShell制作的,它包含用于不同任务的模块文件.一个任务当前失败,构建服务器未检测到错误,因为我的启动构建脚本仍返回0.

Ves*_*per 5

$lastExitCode如果最后一个脚本/程序退出失败,您应该查询具有非零值.所以,你的样本test1.ps1应该是这样的:

. C:\path\to\test2.ps1
if ($lastexitcode -ne 0) { exit $lastexitcode} 
exit 5
Run Code Online (Sandbox Code Playgroud)