gpt4 book ai didi

powershell - 点源 PowerShell 脚本文件和返回代码

转载 作者:行者123 更新时间:2023-12-01 19:15:07 25 4
gpt4 key购买 nike

下面是一些 PowerShell 代码:

测试.ps1:

. C:\path\to\test2.ps1
exit 5

测试2.ps1:

exit 7

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

echo %errorlevel%

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

无论如何调用,如何真正终止脚本并返回结果代码?

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

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

最佳答案

您应该查询 $lastExitCode,如果最后一个脚本/程序失败退出,该查询将具有非零值。因此,您的示例的 test1.ps1 应如下所示:

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

关于powershell - 点源 PowerShell 脚本文件和返回代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31475876/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com