Batch file does action after it's closed - windows

I want to create a batch file, that detects when the CMD window gets closed and does directly after an action.
If for example the the textfile text.txt is opened, and after i launch the batch file called prog.bat with this code inside:
#echo off
echo Hello
pause
How can i tell the batch that if the CMD window which is currently opend, should taskill text.txt file when somebody closes the CMD window?(by closing with ending process or hitting the X on the top)

This is the accepted answer at this question:
#echo off
if "%1" equ "Restarted" goto %1
start "" /WAIT /B "%~F0" Restarted
echo Execute here anything you want when the Batch file is closed...
goto :EOF
:Restarted
echo Hello
pause
exit

Im not one of the best but you could do this.
You need to create 3 files.
Start.bat
#echo off
TITLE Start.bat
REM :: THIS FILE OPEN'S THE CHECK WINDOW BATCH ::
start Init2.bat
ping localhost -n 1 >nul
REM :: IF I WOULDN'T HAVE THE "PING" THE CHECK WINDOW BATCH WOULD BE ON TOP ::
start Init1.bat
Init1.bat
#echo off
REM :: YOU CAN WRITE WHAT YOU WANT HERE ::
REM :: YOUST REMEMBER TO CHANGE "Init2.bat" WHEN YOU CHANGE THE TITLE ::
TITLE Init1.bat
echo.HELLO
pause>nul
Init2.bat
#echo off
SETLOCAL ENABLEDELAYEDEXPANSION
TITLE Init2.bat
:Start
REM :: GET PID ::
set "PID="
for /F "skip=3 delims=" %%A in ('TASKLIST /FI "WINDOWTITLE eq Init1.bat"') do (
set "A=%%A"
set "A=!A:~26,8!"
set "A=!A: =!"
set "PID=!A!"
set "A="
echo.!PID!
goto Test
)
REM :: IF NO WINDOWS NAMED "Init1.bat" exit ::
if not defined "PID" (
echo.No Window!
goto Exit
)
:Test
set "true=0"
for /F "skip=3 delims=" %%A in ('TASKLIST /FI "PID eq !PID!"') do (
set "true=1"
)
REM :: IF WINDOW CLOSED ::
if "!true!" EQU "0" (
echo.No Window!
goto Exit
)
goto Test
:Exit
REM :: HERE ARE YOU WRITING THE CLOSING FILE ::
ren testtxt.txt prog.bat
echo.#echo off > prog.bat
echo.echo hello >> prog.bat
echo.pause >> prog.bat
exit
Hope this help.
This is not a wiki answer, but i hope you find it helpful.
The only thing is that you have a window behind the first, but it works.

Related

Batch: How to scroll through files to read to a variable?

I'm trying to have it scroll through a directory and present a new variable when the user replies "N". I have it all figured out except how to go to the next variable.
cd "C:\Test"
for /r %%F in (*) do SET Show=%%~NF
echo %Show%
echo.
SET /P Continue=Continue?(Y/N)
if /I "%Continue%" EQU "y" goto :Run
if /I "%Continue%" EQU "n" goto :Start
If you're looking to scroll the directory and prompt the user the file name and have them choose to choose it or continue, then bellow should help you.
Firstly, we can use dir /b /a:d to display only directories (folders) in the the current directory. By using a code block ( & ) we can put batch script inside the for loop. For your sake, we can use the CHOICE command to prompt to continue the loop or to save current folder to string and do something with it.
ScrollTreeWithPrompt.bat:
#echo off
setlocal EnableDelayedExpansion
Rem | Configuration
Set "MainDir=C:\Test"
Rem | Get Each Project Folder
for /f "tokens=*" %%A in ('dir "!MainDir!\" /b /a:d') do (
Cls
Echo Current Folder: %%A
echo(
CHOICE /M "Continue?"
Rem | Check for "N" - If so Set String & goto
IF "!ERRORLEVEL!"=="2" (
Set "Choice=%%A"
GOTO Run
)
)
Rem | No Further Results
Cls
Echo Warning: No further folders found.
pause>NUL
goto :EOF
:Run
Cls
echo Currently selected: !MainDir!\!Choice!
pause>NUL
goto :EOF
I have left a few Rem comments in the script to help you along. For any more help on the commands, type the following into a command prompt:
choice /?
set /?
for /?
goto /?
Is this what you need:
For /R "C:\Test" %%A In (*) Do (Choice /M "%%~nA"
If Not ErrorLevel 2 (Set "Show=%%~nA" & GoTo Run))
Exit /B
:Run
Echo Running against %Show%
Pause
Alternatively, should you wish to return to the loop after running against the file name, then use Call instead of GoTo:
For /R "C:\Test" %%A In (*) Do (Choice /M "%%~nA"
If Not ErrorLevel 2 Call :Run "%%~nA")
Exit /B
:Run
Set "Show=%~1"
Echo Running against %Show%
Pause

Windows batch user input variable is not set within an if

I have a program which has following flow. Problem is the windows batch file doesn't properly checks errorlevel and doesn't set KILLSTS value. Could you please let me know what's wrong with this program and how to fix this?
Ask user to open an exe
if Yes
check exe is running or not
if running, ask user whether to close that exe
if yes close exe
run the exe
else
exit
Here is the sample batch file.
#ECHO OFF
#REM SETLOCAL ENABLEEXTENSIONS
SET /P AREYOUSURE="Open Spring STS [y/n]>"
set AREYOUSURE=%AREYOUSURE:~0,1%
ECHO AREYOUSURE=%AREYOUSURE:~0,1%
IF /I %AREYOUSURE% == N (
SET /A errno^|=%ERROR_OTHERCOMMAND_FAILED%
echo Existing Batch
EXIT /B %errno%
)
SETLOCAL
#REM SET KILLSTS=Y
tasklist /fi "IMAGENAME eq STS.exe" |find ":" > nul
ECHO Error %errorlevel%
IF %errorlevel% neq 0 (
SETLOCAL
SET /P KILLSTS="Spring STS is running. Kill STS Process [y/n]>"
echo KILLSTS %KILLSTS%
set KILLSTS=%KILLSTS:~0,1%
echo KILLSTS AFTER SUBSTR %KILLSTS%
IF /I %KILLSTS% == Y TASKKILL /f /im "STS.exe"
ENDLOCAL
)
START "" "C:\sts-bundle\sts-3.8.3.RELEASE\STS.exe"
I am getting below error
You need to learn how to properly format if statements.
You are formatting them as:
IF /I %KILLSTS% == Y TASKKILL /f /im "STS.exe"
When they should be formatted as:
if /i "%KILLSTS%"=="Y" (TASKKILL /f /im STS.exe)
The formatting doesn't really matter as such in simple batch files, but it's best to use the correct syntax which can handle special characters such as SPACES, AMPERSANDS, QUOTES, PIPE for when more complex variables are involved.
Updated script:
#ECHO OFF
#REM SETLOCAL ENABLEEXTENSIONS
SET /P "AREYOUSURE=Open Spring STS [y/n]>"
set "AREYOUSURE=%AREYOUSURE:~0,1% "
echo "AREYOUSURE=%AREYOUSURE:~0,1%"
IF /I "%AREYOUSURE%"=="N" (
SET /A errno^|=%ERROR_OTHERCOMMAND_FAILED%
echo Existing Batch
EXIT /B %errno%
)
SETLOCAL
#REM SET KILLSTS=Y
tasklist /fi "IMAGENAME eq STS.exe" | find ":" > nul
ECHO Error %errorlevel%
IF "%errorlevel%" neq "0" (
call :escapeexpansion
)
START "" "C:\sts-bundle\sts-3.8.3.RELEASE\STS.exe"
exit /b
:escapeexpansion
SETLOCAL
SET /P "KILLSTS=Spring STS is running. Kill STS Process [y/n]>"
echo KILLSTS %KILLSTS%
set "KILLSTS=%KILLSTS:~0,1%"
echo KILLSTS AFTER SUBSTR %KILLSTS%
IF /I "%KILLSTS%"=="Y" TASKKILL /f /im "STS.exe"
ENDLOCAL
goto :EOF
The entire structure seems wrong to me; as well as pointlessly using SET /P instead of CHOICE.
#ECHO OFF
TASKLIST /FI "IMAGENAME eq STS.exe"|FIND ":">NUL 2>&1&&GOTO ASKIF
CHOICE /M "Spring STS is running. Kill STS Process"
IF ERRORLEVEL 2 GOTO ENDIT
TASKKILL /F /IM "STS.exe"
TIMEOUT 3 /NOBREAK>NUL
:ASKIF
CHOICE /M "Open Spring STS"
IF ERRORLEVEL 2 GOTO ENDIT
START "" "C:\sts-bundle\sts-3.8.3.RELEASE\STS.exe"
:ENDIT
Echo=Exiting Batch
TIMEOUT 3 /NOBREAK>NUL

Find opened process in Windows batch

I'm trying to write code which loops and tells if a certain process is opened or not. It should be a loop that will show me in real time if the process is opened or not. In other words, a text will change when the program is opened and change again when it's closed. Instead what I got was a flood with the same text and it doesn't show the 'echos' below it.
I tried this:
#echo off
goto xera
:start
tasklist /FI "IMAGENAME eq notepad.exe" | find /I "notepad.exe" > nul
IF %ERRORLEVEL% equ 0 ECHO is opened
IF %ERRORLEVEL% equ 1 ECHO isnt opened
:xera
set /p "=Status: " <nul &call :start //the code got 'stuck' here
ECHO Text 2 (doesnt show)
pause>nul
You are not terminating your sub-routine :start correctly. Try the following:
#echo off
goto xera
:start
tasklist /FI "IMAGENAME eq notepad.exe" | find /I "notepad.exe" > nul
IF %ERRORLEVEL% equ 0 ECHO is opened
IF %ERRORLEVEL% equ 1 ECHO isnt opened
exit /b
:xera
set /p "=Status: " <nul &call :start
ECHO Text 2 (doesnt show)
pause>nul
I inserted exit /b which tells the command interpreter to return to the command after the call statement that actually called it. You could also use goto :EOF instead. Type call /? for more information on how to call sub-routines in batch.

Bat File that will read the server file and then restart based on output of server file

So far I've been trying to make a continuous .bat file that will start the server file, read every line that comes down and if the response "Server has become unresponsive" then the bat will close the file and re-open(this needs to be done every hour or so and I'm not always at the computer)
I do believe this is the correct code but I need to double check with some tech-savy minds to see if it's correct.
#echo off
SETLOCAL DisableDelayedExpansion
FOR /F "usebackq delims=" %%A in (`"findstr rust_server/n ^^ "`) do (
set "myVar=%%A"
call :processLine myVar
)
goto :eof
:processLine
SETLOCAL EnableDelayedExpansion
set "line=!%1!"
set "line=!line:*:=!"
echo(!line!
Find /I /V "Unresponsive for 10"
taskkill /fi "WindowTitle eq rust_server*"
start /d "C:\Rust Server" rust_server.exe
ENDLOCAL
goto :eof
Any ideas/suggestions would be greatly appreciated.
#Echo off
Title SERVER RESTARTER (place with your rust_server exe)
color 1f
SET n=0
:Loop
SET /A n=n+1
echo Server Restarter
echo -----Restart Server Batch VERSION-----
taskkill /IM rust_server.exe
echo Opening rust_server.exe server again
rust_server.exe
if %n% EQU 60 (
exit
) Else if %n% LEQ 24 (
Goto Loop

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

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.
The problem is that I can't safely predict whether potential user would use GUI or CLI. If somebody using GUI double-clicks this script in Explorer window, they won't have chance to read anything, unless I pause the window. If they use CLI, pause will bother them.
So I'm looking for a way to detect it.
#echo off
if _%1_==__ (
echo usage: %nx0: filename
rem now pause or not to pause?
)
Is there a nice solution on this?
You can check the value of %CMDCMDLINE% variable. It contains the command that was used to launch cmd.exe.
I prepared a test .bat file:
#Echo Off
echo %CMDCMDLINE%
pause
When run from inside of open cmd.exe window, the script prints "C:\Windows\system32\cmd.exe".
When run by double-clicking, it prints cmd /c ""C:\Users\mbu\Desktop\test.bat" "
So to check if your script was launched by double-clicking you need to check if %cmdcmdline% contains the path to your script. The final solution would look like this:
#echo off
set interactive=1
echo %cmdcmdline% | find /i "%~0" >nul
if not errorlevel 1 set interactive=0
rem now I can use %interactive% anywhere
if _%1_==__ (
echo usage: %~nx0 filename
if _%interactive%_==_0_ pause
)
Edit: implemented fixes for issues changes discussed in comments; edited example to demonstrate them
:: exit if not interactive
echo %CMDCMDLINE% | find /i "/c"
if not ERRORLEVEL 1 goto:eof
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
This is only using the internal command. so effectively....
EnableDelayedExpansion
if "!cmdcmdline!" neq "!cmdcmdline:%~f0=!" pause >nul
or
if not "!cmdcmdline!" == "!cmdcmdline:%~f0=!" pause >nul
DisableDelayedExpansion
if "%cmdcmdline%" neq "%cmdcmdline:%~f0=%" pause >nul
or
if not "%cmdcmdline%" == "%cmdcmdline:%~f0=%" pause >nul
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
)
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...
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...
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
setlocal EnableDelayedExpansion
if "!cmdcmdline!" neq "!cmdcmdline:%comspec%=!" ( pause>nul )
Test is done in Windows 10. Using %windir%, it is a little dangerous or ambiguous. So %comspec% is super safe.

Resources