I have a bat file that does a bunch of things and closes the cmd window which is fine when user double clicks the bat file from explorer. But if I run the bat file from a al
You can add a command line parameter when running from a CMD window that won't exist when the file is double-clicked. If there is no parameter, close the window. If there is, don't close it. You can test the parameter using %1
You also can check for SESSIONNAME
environment variable.
As you see here that variable typically isn't set in Explorer window. When invoking from cmd it SESSIONNAME
is set to Console
. I can confirm this for Windows 10.
Unfortunately behaviour seems to be changeable: https://support.microsoft.com/de-de/help/2509192/clientname-and-sessionname-enviroment-variable-may-be-missing
mousio's solution is nice; however, I personally did not manage to make it work in an "IF" statement because of the double quotes in the value of %cmdcmdline%
(with or without double quotes around %cmdcmdline%
).
In constrast, the solution using %0
works fine. I used the following block statement and it works like a charm:
IF %0 == "%~0" pause
The following solution, which expands %~0
to a fully qualified path, might also work if the previous does not (cf. Alex Essilfie's comment):
IF %0 EQU "%~dpnx0" PAUSE
However, note that this solution with %~dpnx0
fails when
%USERPROFILE%
directory, and%USERNAME%
contains one or more uppercase charactersbecause... wait for it... the d
in %~dpnx0
forces your %USERPROFILE%
username to lowercase, while plain %0
does not. So they're never equal if your username contains an uppercase character. ¯\_(ツ)_/¯
A consolidated answer, derived from much of the information found on this page:
:pauseIfDoubleClicked
setlocal enabledelayedexpansion
set testl=%cmdcmdline:"=%
set testr=!testl:%~nx0=!
if not "%testl%" == "%testr%" pause
Naturally, if you want to do something else if you detect a double-click, you can change the pause.
Thanks everyone.
Build upon the other answers, I find the most robust approach to:
x
to enable text comparison without breaking the IF statement.x
).set "dclickcmdx=%systemroot%\system32\cmd.exe /c xx%~0x x"
set "actualcmdx=%cmdcmdline:"=x%"
set isdoubleclicked=0
if /I "%dclickcmdx%" EQU "%actualcmdx%" (
set isdoubleclicked=1
)
This adds more robustness against general cmd /c
calls, since Explorer adds an awkward extra space before the last quote/x (in our favor). If cmdcmdline
isn't found, it correctly renders isdoubleclicked=0
.
Like @anishsane I too wanted a pause statement if launched from explorer, but not when launched from a command window.
Here's what worked for me, based upon @mousio's answer above:
@SET cmdcmdline|FINDSTR /b "cmdcmdline="|FINDSTR /i pushd >nul
@IF ERRORLEVEL 1 (
@echo.
@echo Press ENTER when done
@pause > nul
)
(Nothing original here, just providing a working example)