Detecting how a batch file was executed

后端 未结 9 1783
伪装坚强ぢ
伪装坚强ぢ 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:24

    I use a parameter "automode" when I run my batch files from scripts.

    set automode=%7
    

    (Here automode is the seventh parameter given.)

    Some code follows and when the file should pause, I do this:

    if @%automode%==@ pause
    
    0 讨论(0)
  • 2020-12-28 09:26

    Just add pause regardless of how it was opened? If it was opened from command prompt no harm done apart from a harmless pause. (Not a solution but just thinking whether a pause would be so harmful / annoying )

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

    I just ran a quick test and noticed the following, which may help you:

    • When run from an open command prompt, the %0 variable does not have double quotes around the path. If the script resides in the current directory, the path isn't even given, just the batch file name.
    • When run from explorer, the %0 variable is always enclosed in double quotes and includes the full path to the batch file.

    This script will not pause if run from the command console, but will if double-clicked in Explorer:

    @echo off
    setlocal enableextensions
    
    set SCRIPT=%0
    set DQUOTE="
    
    @echo do something...
    
    @echo %SCRIPT:~0,1% | findstr /l %DQUOTE% > NUL
    if %ERRORLEVEL% EQU 0 set PAUSE_ON_CLOSE=1
    
    :EXIT
    if defined PAUSE_ON_CLOSE pause
    

    EDIT: There was also some weird behavior when running from Explorer that I can't explain. Originally, rather than

    @echo %SCRIPT:~0,1% | findstr /l %DQUOTE% > NUL
    if %ERRORLEVEL% EQU 0 set PAUSE_ON_CLOSE=1
    

    I tried using just an if:

    if %SCRIPT:0,1% == ^" set PAUSE_ON_CLOSE=1
    

    This would work when running from an open command prompt, but when run from Explorer it would complain that the if statement wasn't correct.

    0 讨论(0)
提交回复
热议问题