在 .BAT 程序中获取 Powershell return 代码

Getting Powershell return code within a .BAT program

我有一个 .BAT 程序,我在其中调用 Powershell 脚本 运行。

当 powershell 完成其工作时,如何在 .BAT 程序中获取退出代码?

编辑:

这对我有用。

call powershell.exe .\MyPowerShellScript.ps1
echo %ERRORLEVEL%

%ERRORLEVEL% 变量将为您提供最后一个 return 代码:

@echo off

call powershell.exe -Command "exit 123"
echo Exited with return code %ERRORLEVEL%

将导致:

C:\> path\to\script.bat
Exited with return code 123

对于脚本,要么使用 -File 参数:

@echo off

call powershell.exe -File "path\to\file.ps1"
echo Exited with return code %ERRORLEVEL%

或使用 & 调用运算符调用脚本:

@echo off

call powershell.exe -Command "& 'C:\path\to\file.ps1'"
echo Exited with return code %ERRORLEVEL%

脚本终止异常也会设置错误级别。

powershell throw

ScriptHalted
At line:1 char:1
+ throw
+ ~~~~~
    + CategoryInfo          : OperationStopped: (:) [], RuntimeException
    + FullyQualifiedErrorId : ScriptHalted


echo %errorlevel%

1