batch-file - 如何同时退出cmd文件和shell?

标签 batch-file cmd

我正在 shell (c:\windows\system32\cmd.exe) 中执行脚本 (.cmd)。我想要的是,当命令返回错误代码时,.cmd 文件结束执行,然后 cmd.exe 也结束执行,将错误代码返回给调用它的文件。

我正在使用这样的东西:

C:\...\gacutil.exe /i C:\...\x.dll
if not errorlevel 0 (
    echo Error registering C:\...\x.dll
    exit %errorlevel%
)

但这行不通。我尝试使用 exit/b 但对我来说看起来一样。有什么想法吗?

最佳答案

出现了every now and then , 恕我直言 exit 和 exit/b 被破坏,因为它们只设置批处理文件使用的错误级别,但它们不设置 cmd.exe 进程的退出代码。

如果批处理脚本正在执行错误级别检查,调用就足够了:

REM DoSomeAction.cmd
@echo off
call someprogram.exe
if errorlevel 1 exit /b 

REM MainScript.cmd
@echo off
...
call DoSomeAction.cmd
if errorlevel 1 (
  ...
)

但是如果你想使用 && 或 ||语法 (myscript.cmd&&someotherapp.exe) 或者您的脚本是从一个程序而不是另一个批处理文件启动的,您实际上想要设置进程退出代码(在父进程中使用 GetExitCodeProcess 检索)

@echo off
call thiswillfail.exe 2>nul
if errorlevel 1 goto diewitherror
...
REM This code HAS to be at the end of the batch file
REM The next command just makes sure errorlevel is 0
verify>nul
:diewitherror
@%COMSPEC% /C exit %errorlevel% >nul

使用“正常”exit/b 然后使用 call myscript.cmd&&someotherapp.exe 调用它确实有效,但您不能假设每个执行的程序批处理文件将创建进程为 cmd.exe/c call yourscript.cmd

关于batch-file - 如何同时退出cmd文件和shell?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4864670/

相关文章:

batch-file - 带有服务停止/启动的通配符

batch-file - 从 FTP 服务器获取文件并将其复制到 UNC 目录

c# - 以不同的用户静默方式通过 C# 代码运行 .bat 文件

Windows 命令解释器 : how to obtain exit code of first piped command

windows - 如何在批处理文件中更改为当前用户的目录

batch-file - COPY 命令以什么顺序将文件从源复制到目标?

windows - 在 Windows CMD FOR 循环中使用 youtube-dl 会去除非 ASCII 字符

php - .txt 写入 .json 文件批处理或需要 php 文件

windows - echo命令在批处理编程中是如何工作的

batch-file - 用于运行批处理文件的 GUI