Created
December 7, 2021 19:10
-
-
Save maphew/9f6ba713d30eb1d0f67e7f0b2a338ba5 to your computer and use it in GitHub Desktop.
Detect if bat file is running via double click or from cmd window
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
T:\ENV.558>if /I "C:\WINDOWS\system32\cmd.exe /c ``T:\ENV.558\setenv-testing.bat` `" EQU "`C:\WINDOWS\system32\cmd.exe` /C ``T:\ENV.558\setenv-testing.bat` `" pause |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@REM https://stackoverflow.com/questions/6961153/is-it-possible-to-distinguish-when-shell-is-run-from-command-line-or-from-other | |
@REM Testing https://stackoverflow.com/a/61511609/14420 by @simon-streicher | |
if /i "%comspec% /c ``%~0` `" equ "%cmdcmdline:"=`%" pause |
@heetbeet here's the test:
bat file:
if /i "%comspec% /c %~0 " equ "%cmdcmdline:"=%"
output:
The syntax of the command is incorrect.
C:\temp>if /i "C:\Windows\system32\cmd.exe /c C:\temp\setenv-testing.bat " equ "C:\Windows\system32\cmd.exe /C C:\temp\setenv-testing.bat "
I have ConEmu installed. I'll also try from a vm that doesn't have it.
Thanks, the command is incorrect because the if statement doesn't follow up with a command, e.g. if /i "%comspec% /c %~0 " equ "%cmdcmdline:"=%" echo Passed
But what I gathered from your output:
The syntax of the command is incorrect.
C:\temp>if /i "C:\Windows\system32\cmd.exe /c C:\temp\setenv-testing.bat " equ "C:\Windows\system32\cmd.exe /C C:\temp\setenv-testing.bat "
It seems like the expansion did match successfully, i.e. lhs "C:\Windows\system32\cmd.exe /c C:\temp\setenv-testing.bat "
equals rhs "C:\Windows\system32\cmd.exe /C C:\temp\setenv-testing.bat "
when using the case insensitive /i
flag.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Please do a test on this variant:
if /i "%comspec% /c %~0 " equ "%cmdcmdline:"=%"
; it strips the quotes completely. This might, though, invite false positives, but it will almost certainly lower false negatives. If it works please let me know, so I can update the original stack overflow accordingly: https://stackoverflow.com/a/61511609/1490584