如何获取调用bat脚本的名称

时间:2017-03-29 09:26:22

标签: batch-file call invoke

我需要拥有2.bat脚本行为,具体取决于调用脚本的名称。

方案: 从许多其他外部脚本调用2.bat,我无权更改。我的拇指只有2.bat

1.bat

...
call 2.bat

2.bat

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

3 个答案:

答案 0 :(得分:3)

由于你无法更改呼叫蝙蝠,如果通过cmd控制台触发它(它可能是一个内存转储可能有帮助吗?)几乎不可能得到它的名字,因为ProcessId只保存{{1 }}。命令提示符历史记录可以为您提供一些信息,但它不可靠(并且需要转储到临时文件)

如果双击呼叫球,您可以使用:

cmd.exe

答案 1 :(得分:0)

您可以通过技巧获取调用批次的名称。

假设您有first.bat(您无法控制),它可能看起来像这样

@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

答案 2 :(得分:0)

我已经稍微调整了jikou和jeb的代码,以便它也可以从调用者脚本中检测到调用者函数。

detectCallerScript.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" %%0 %*
    ) else (
        set "callType=cmd-line"
        cmd /c "call "%~d0\:mainFunc\..%~pnx0" %%0 %*"
    )
    endlocal
)
echo(NEVER REACHED
exit /b

:mainFunc
set "source=%~1"
shift /1
:mainFuncLoop
set args=%args%%1 
if "%~2" neq "" shift /1&goto:mainFuncLoop
if defined args set "args=%args:~0,-1%"
echo(:mainFunc of %~nx0 source=%source% with args="%args%" is called from '%caller%'/%callType%
exit /b

scriptCaller.bat:

@echo off
set caller=empty
echo(%~0: call detectCallerScript hi there
call detectCallerScript hi there
echo(Back to %~0
echo(
call:someFunc
exit /b

:someFunc
set caller=empty
echo(%~n0 %~0: call detectCallerScript hi there
call detectCallerScript hi there
echo(Back to %~0
echo(

输出:

scriptCaller.bat: call detectCallerScript hi there
:mainFunc of detectCallerScript.bat source=scriptCaller.bat with args="hi there" is called from '{path}\scriptCaller.bat'/batch
Back to scriptCaller.bat

scriptCaller :someFunc: call detectCallerScript hi there
:mainFunc of detectCallerScript.bat source=:someFunc with args="hi there" is called from '{path}\scriptCaller.bat'/batch
Back to :someFunc