首页 > 解决方案 > 在 .BAT 程序中获取 Powershell 返回代码

问题描述

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

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

编辑:

这对我有用。

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

标签: powershellbatch-filebatch-processing

解决方案


%ERRORLEVEL%变量将为您提供最后的返回码:

@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%

推荐阅读