使用 Powershell Start-Process 运行 Cmd Batch 文件,如何从 Cmd Batch 文件中读取错误级别?

Using Powershell Start-Process to run a Cmd Batch file, how to read the error level from the Cmd Batch file?

假设我有两个文件,script.ps1filename.cmd,并且我从 Powershell 提示 运行 .\script.ps1

脚本.ps1

Write-Host "About to run filename.cmd"
$proc = Start-Process -FilePath filename.cmd -NoNewWindow -Wait
Write-Host "proc: [$proc]"
Write-Host "LASTEXITCODE: [$LASTEXITCODE]

filename.cmd

@echo off
ECHO File returns ErrorLevel=1
exit /b 1

输出:

About to run filename.cmd
proc: []
LASTEXITCODE: []

procLASTEXITCODE都是$null。我的理解是我可以通过某种方式访问​​ ErrorCode?

如何在我的 Powershell 脚本中读取失败的错误级别(在本例中为 1)?

要同步执行控制台应用程序,包括批处理文件,请直接调用它们不要使用Start-Process - 见 this answer.

因此:

Write-Host "About to run filename.cmd"
# For security reasons, PowerShell requires that you explicitly
# signal the intent to run an executable located *in the current directory*,
# hence the need for `./` (or `.\`)
# Only direct invocation of external programs (batch files) sets
# the automatic $LASTEXITCODE variable.
./filename.cmd
Write-Host "LASTEXITCODE: [$LASTEXITCODE]

至于你试过的

Start-Process outputs nothing by default - except if you pass the -PassThru switch, in which case a System.Diagnostics.Process 代表新启动进程的实例被返回。

假设您还指定了 -Wait,就像您的情况一样,您随后可以访问返回对象的 .ExitCode 属性 以确定之后的退出代码。

注意automatic variable $LASTEXITCODE只在直接调用外部程序后设置,如上图

因此,如果您要使用 Start-Process - 在这种情况下 而不是 ,如上所述 - 您必须使用以下内容:

Write-Host "About to run filename.cmd"
$proc = Start-Process -PassThru -FilePath filename.cmd -NoNewWindow -Wait
Write-Host "proc: [$proc]"
Write-Host "exit coe: [$($proc.ExitCode)]