批处理文件中的退出代码不会传播到父 powershell 脚本 [英] Exit code from a batch file is not propagated to the parent powershell script

查看:22
本文介绍了批处理文件中的退出代码不会传播到父 powershell 脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请注意:

c:\temp\1.cmd

@echo off
setlocal

cmd /c dir aaa
IF %ERRORLEVEL% NEQ 0 GOTO fail
GOTO end
:fail
echo - Script failed

:end
endlocal

现在如果我在命令提示符下运行它:

Now if I run it in the command prompt:

C:\temp> cmd
Microsoft Windows [Version 10.0.16299.967]
(c) 2017 Microsoft Corporation. All rights reserved.

C:\temp>c:\temp\1.cmd
 Volume in drive C has no label.
 Volume Serial Number is 4A5E-F223

 Directory of C:\temp

File Not Found
- Script failed

C:\temp>echo %errorlevel%
1

C:\temp>

现在我从 Powershell 运行它:

Now I am running it from Powershell:

C:\temp> $PSVersionTable

Name                           Value
----                           -----
PSVersion                      5.1.16299.967
PSEdition                      Desktop
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0...}
BuildVersion                   10.0.16299.967
CLRVersion                     4.0.30319.42000
WSManStackVersion              3.0
PSRemotingProtocolVersion      2.3
SerializationVersion           1.1.0.1


C:\temp> cmd /c C:\temp\1.cmd
 Volume in drive C has no label.
 Volume Serial Number is 4A5E-F223

 Directory of C:\temp

File Not Found
- Script failed
C:\temp> $LASTEXITCODE
0
C:\temp>

据我所知,退出代码应该正确传播.那么,问题出在哪里?

From what I know the exit code is supposed to propagate correctly. So, what is the problem?

推荐答案

第一:ERRORLEVEL 不是 %ERRORLEVEL%.

其次,errorlevel 与进程退出代码不同.

Second, the errorlevel is not the same as a process exit code.

尝试如下更改您的 cmd 脚本(注意添加了exit/b 1"):

Try altering your cmd script as follows (note the addition of "exit /b 1"):

@echo off
setlocal

cmd /c dir aaa
IF %ERRORLEVEL% NEQ 0 GOTO fail
GOTO end
:fail
echo - Script failed
exit /b 1

:end
endlocal

这篇关于批处理文件中的退出代码不会传播到父 powershell 脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆