Detecting how a batch file was executed

后端 未结 9 1779
伪装坚强ぢ
伪装坚强ぢ 2020-12-28 08:24

Assuming Windows, is there a way I can detect from within a batch file if it was launched from an open command prompt or by double-clicking? I\'d like to add a pause to the

相关标签:
9条回答
  • 2020-12-28 09:07

    Don't overlook the solution of having two batch files:
    abatfile.bat and abatfile-with-pause.bat
    The second simply calling the first and adding a pause

    0 讨论(0)
  • Yes. Patrick Cuff's final example almost worked, but you need to add one extra escape, '^', to make it work in all cases. This works great for me:

    set zero=%0
    if [^%zero:~0,1%] == [^"] pause
    

    However, if the name of the batch file contains a space, it'll be double quoted in either case, so this solution won't work.

    0 讨论(0)
  • 2020-12-28 09:08

    One easy way to do it is described here: http://steve-jansen.github.io/guides/windows-batch-scripting/part-10-advanced-tricks.html There is little typo in the code mentioned in the link. Here is correct code:

    @ECHO OFF
    SET interactive=0
    
    ECHO %CMDCMDLINE% | FINDSTR /L /I %COMSPEC% >NUL 2>&1
    IF %ERRORLEVEL%==0 SET interactive=1
    
    ECHO do work
    
    IF "%interactive%"==1 PAUSE
    EXIT /B 0
    
    0 讨论(0)
  • 2020-12-28 09:10

    crazy idea: use tasklist and parse it's results. I've wrote in a test batch file:

    tasklist > test.out

    and when I double-clicked it, there was an additional "cmd.exe" process just before the tasklist process, that wasn't there when the script was run from command line (but note that might not be enough if someone opens a command line shell and then double-click the batch file)

    0 讨论(0)
  • 2020-12-28 09:13

    Similar to a second batch file you could also pause if a certain parameter is not given (called via clicking).

    This would mean only one batch file but having to specify a -nopause parameter or something like that when calling from the console.

    0 讨论(0)
  • 2020-12-28 09:15

    Here's what I use :

    rem if double clicked it will pause
    for /f "tokens=2" %%# in ("%cmdcmdline%") do if /i "%%#" equ "/c" pause
    
    0 讨论(0)
提交回复
热议问题