首页 > 解决方案 > 从 Python 获取 Powershell 脚本的返回码

问题描述

编辑清理信息:

我正在编写一个将调用另一个脚本的 PowerShell 脚本。

一旦我得到返回码,我想在一个if语句中使用它:

我的代码:

if ($LASTEXITCODE -eq $TRUE) {
# Start job.
} else {
# Send failed email
}

编辑 2:正确的格式,如:Ansgar Wiechers

**if ($LASTEXITCODE -eq 0)** {
# Start job.
} else {
# Send failed email
}

标签: pythonpowershell

解决方案


正如@AnsgarWiechers 提到的,您应该明确地测试$LASTEXITCODE -eq 0而不是$true.

这是您示例的简单代码段:

test.py内容:

import sys
print(f'Testing for {sys.argv}')
assert sys.argv[1] == 'Success'

test.ps1内容:

py test.py Fail # or Success
if ($LASTEXITCODE -eq 0) {
    Write-Output "Python script ran successfully"
}
else {
    Write-Output "Python script failed"
}

结果:

Testing for ['test.py', 'Success']
Python script ran successfully

# ...

Testing for ['test.py', 'Fail']
Traceback (most recent call last):
  File "test.py", line 5, in <module>
    assert sys.argv[1] == 'Success'
AssertionError
Python script failed

推荐阅读