Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I prevent a Windows batch file from execution through a double-click?

Is it possible to setup a Windows .BAT file in such a way so that it's possible to execute when called from CMD, but does not run when someone double-clicks the file?

like image 233
IDDQD Avatar asked Dec 23 '22 01:12

IDDQD


2 Answers

The environment variable %cmdcmdline% contains the command line used to launch CMD.exe. If a batch file was launched from a click in Explorer or on the Desktop, it will be:

C:\Path\To\cmd.exe /c ""c:\path\to\batch\file.bat" "

The full path to the batch file can also be accessed as %~f0 within the batch file itself to compare with that variable.

like image 54
Govind Parmar Avatar answered Jan 27 '23 10:01

Govind Parmar


Would you like get try this coding suggest doing this job...

Basically, use findstr to check the if the variable %cmdcmdline% value match this .cmd or .bat, if this return positively then goto :eof (exit), but, if not, then run your code...

  @echo off & cd /d %~dp0" 

  echo/%cmdcmdline% | findstr /i "\.cmd \.bat" 2>nul && ( 

    title... by click.. & echo/%cmdcmdline% | findstr "%0" 

    echo/ bat: "%0" running by click

    timeout /t 5 /nobreak>nul & goto :eof

    ) || (

    title... by command line.. && echo/%cmdcmdline%| findstr "%0" 

    echo/ bat: "%0" running by command line 

    timeout /t 5 /nobreak>nul & goto :run_code

   )

  :run_code

  echo/ your code enter here

  ::  ....

  goto :eof

1st by click & 2nd by command line

like image 39
Io-oI Avatar answered Jan 27 '23 11:01

Io-oI