2015-04-16 29 views
2

我需要區分內部script.cmd這兩種情況:如何在Windows CMD.EXE shell中檢測腳本是否被CALL或直接調用?

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. 

任何人都知道了「魔高一尺這​​裏」,這將檢測到已經CALL'ed和集調用= 1?

+0

這並不解決什麼問題? –

+0

它解決了能夠做的問題... 'script1.cmd && script2.cmd && script3.cmd' ...無需做... 'call script1.cmd && call script2.cmd && call script3.cmd' –

+0

不,不知道如何調用該文件,指出的「問題」不能被「解決」。批處理解釋器決定執行流程是否返回給調用者(使用'call')或不使用'call'時。並且在您的評論中的示例代碼中,在兩種情況下調用這三個文件都沒有問題 –

回答

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批處理文件必須在批處理文件中的最後一個代碼

+0

我結束了使用相同的技術。仍然看起來它應該是某種方式可以訪問。現在我希望當我在微軟工作時,我會看看CMD源代碼。 * sadpanda * –

+0

謹慎的話,如果你需要'script1^| | && script2 ^> && script3''%*'不能正確地轉義轉義參數。在我的用例中,這不是一個問題,因爲我的參數很簡單。但是我在單元測試中發現這是一個問題。我可能錯過了一個'%〜*'或其他適當擴展參數的東西。 –

+0

太麻煩了。我推薦PowerShell。 –

相關問題