Determining if batch script has been started/executed from the command line (cmd) -or- To pause or not to pause?

后端 未结 9 1990
眼角桃花
眼角桃花 2021-02-01 17:34

I like to have a typical \"usage:\" line in my cmd.exe scripts — if a parameter is missing, user is given simple reminder of how the script is to be used.

相关标签:
9条回答
  • 2021-02-01 17:54

    Here, I wrote something...

    Usage.bat


    @echo off
    if arg%1==arg goto help
    goto action
    
    :action
    echo do something...
    goto end
    
    :help
    set help1=This is Help line 1.
    set help2=This is Help line 2.
    cmd.exe /k "echo %help1% &echo %help2%"
    goto end
    
    :end
    

    It's not perfect, but it works! :D

    -joedf

    0 讨论(0)
  • 2021-02-01 17:54

    Similar approach...

    setlocal
    
    set startedFromExplorer=
    echo %cmdcmdline% | find /i "cmd.exe /c """"%~0""" >nul
    if not errorlevel 1 set startedFromExplorer=1
    
    ...
    
    if defined startedFromExplorer pause
    goto :EOF
    
    0 讨论(0)
  • 2021-02-01 17:59

    Start your batch checking for %WINDIR% in %cmdcmdline% like this:

    echo "%cmdcmdline%" | findstr /ic:"%windir%" >nul && (
      echo Interactive run of: %0 is not allowed
      pause
      exit /B 1
    )
    
    0 讨论(0)
  • 2021-02-01 17:59

    for internal command

    setlocal EnableDelayedExpansion
    set "cmddiff=!cmdcmdline:~0,1!" & if !cmddiff! neq ^" ( pause >nul )
    endlocal
    

    or

    setlocal EnableDelayedExpansion
    set "cmddiff=!cmdcmdline:~28,1!" & if !cmddiff! neq ^" ( pause >nul )
    endlocal
    

    You can compare the different thing, but this is only worked within EnableDelayedExpansion. and I don't think that this will be always worked, cause windows version, etc...

    0 讨论(0)
  • 2021-02-01 18:00
    :: exit if not interactive
    echo %CMDCMDLINE% | find /i "/c"
    if not ERRORLEVEL 1 goto:eof
    
    0 讨论(0)
  • 2021-02-01 18:01

    Please use findstr

    echo %cmdcmdline% | findstr /ic:"%~f0" >nul && ( pause >nul )
    

    or

    setlocal EnableDelayedExpansion
    .
    .
    echo !cmdcmdline! | findstr /ic:"%~f0" >nul && ( pause >nul )
    .
    .
    endlocal
    

    This is always worked...

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