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?
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With