2017-03-29 94 views
1

根據調用腳本的名稱,我需要具有我的2.bat腳本行爲。如何獲取調用蝙蝠腳本的名稱

場景: 2.bat從許多其他外部腳本中調用,我無權更改。只有2.bat在我的拇指下。

1.bat

... 
call 2.bat 

2.bat

...here place something extracting "1.bat"... 
+7

[批處理(.bat)的可能重複:獲取第一個腳本的名稱,而不是當前的名稱](http://stackoverflow.com/questions/10087812/batch-bat-get-the-name-of-the-first-script-not-the-current-一) – geisterfurz007

回答

3

正如你不能改變主叫蝙蝠會出現幾乎是不可能的,如果它是通過CMD控制檯觸發得到它的名字(可能是內存轉儲可以幫助嗎?),因爲ProcessId將只保存cmd.exe的信息。命令提示符歷史可以給你一些信息,但它是不可靠的(並需要轉儲到一個臨時文件)

如果調用蝙蝠被雙擊您可以使用此:

setlocal enableDelayedExpansion 
for /f "tokens=2* delims= " %%a in ("%cmdcmdline%") do (
    if /i "%%~a" equ "/c" (
     for %%# in (%%~b) do (
      echo calling bat : %%~# 
     ) 
    ) else (
     doskey /history >"%tmp%\cmd.history" 
     for /f "usebackq tokens=* delims=" %%# in ("%tmp%\cmd.history") do (
      set "last_command=%%#" 
     ) 
     echo probably this is the calling bat: !last_command! 
     del /q /f "%tmp%\cmd.history" 
    ) 
) 


pause 
0

你可以得到調用批次的名稱。

假設你有一個first.bat(你不能CONTROLL)它可能看起來像這樣

@echo off 
set caller=empty 
echo This is %~0 

for /L %%n in (1 1 3) do (
    echo(
    echo #1 before calling, n=%%n 
    call second %%n 
) 

echo Back to %~0 

和你second.bat檢測來電

@echo off 
setlocal DisableDelayedExpansion 
set "func=%~0" 
for /F "delims=\" %%X in ("%func:*\=%") do set "func=%%X" 
if ":" == "%func:~0,1%" (
    goto %func% 
) 
REM *** Get the name of the caller 
(
    (goto) 2>nul 
    setlocal DisableDelayedExpansion 
    call set "caller=%%~f0" 
    call set _caller=%%caller:*%%~f0=%% 
    if defined _caller (
     set "callType=batch" 
     call "%~d0\:mainFunc\..%~pnx0" %* 
    ) ELSE (
     set "callType=cmd-line" 
     cmd /c "call "%~d0\:mainFunc\..%~pnx0" %*" 
    ) 
    echo BACK 
    endlocal 
) 
echo NEVER REACHED 
exit /b 

:mainFunc 
echo :mainFunc of %~nx0 arg1=%1 is called from '%caller%'/%callType% 
exit /b