如何检测脚本是在 Windows CMD.EXE shell 中被调用还是被直接调用?

How do I detect if script was CALL'ed or invoked directly, in Windows CMD.EXE shell?

我需要在里面区分这两种情况script.cmd:

C:\> call script.cmd
C:\> script.cmd

如何确定我的 script.cmd 是直接调用的,还是在使用 CALL 的上下文中调用的?

如果重要,请在 Windows 7.

@echo off
set invoked=0
rem ---magic goes here---
if %invoked%==0 echo Script invoked directly.
if %invoked%==1 echo Script invoked by a CALL.

有谁知道 "magic goes here" 会检测到已被 CALL'ed 并设置 invoked=1 吗?

此时此刻,我看不出有什么办法可以检测到它,但作为一种解决方法,您始终可以强制使用哨兵。

@echo off
    setlocal enableextensions
    rem If "flag" is not present, use CALL command
    if not "%~1"=="_flag_" goto :useCall
    rem Discard "flag"
    shift /1

    rem Here the main code

    set /a "randomExitCode=%random% %% 2"   
    echo [%~1] exit with code %randomExitCode%
    exit /b %randomExitCode%
    goto :eof


rem Retrieve a correct full reference to the current batch file    
:getBatchReference returnVar
    set "%~1=%~f0" & goto :eof

rem Execute     
:useCall
    setlocal enableextensions disabledelayedexpansion
    call :getBatchReference _f0
    endlocal & call "%_f0%" _flag_ %*

这将允许您使用指示的语法

script.cmd first && script.cmd second && script.cmd third

发布的代码以随机退出代码结束脚本以进行测试。当退出代码为 0

时,将继续执行

注意:为了让它工作,至少在 XP 中,批处理文件的 call 似乎必须是批处理文件中的最后一个代码