batch - run command series on new window - windows

First thing fist, this is the first attempt with batch.
I am writing a small utility script that executes very simple tasks, and I have already pretty much everything in place.
What I want to do is execute some of the actions in a different command window.
I managed to get a new window to open, but the problem I've got is that it exectues the first command only, and the second one still runs on the first window.
Here's some code:
ECHO OFF
CLS
:MENU
ECHO.
ECHO 1 - tail - Error
ECHO 2 - tail - Access
ECHO -----------------------------
ECHO X - Close
SET /P M=Select the action number then press ENTER:
IF %M%==1 GOTO error
IF %M%==2 GOTO access
IF %M%==X GOTO EOF
:error
ECHO.
start cmd /K ssh web
sleep 5
tail -f /var/log/apache2/error.log
GOTO MENU
:access
ECHO.
start cmd /K ssh web
sleep 5
tail -f /var/log/apache2/access.log
GOTO MENU
with this code, the new window opens and the ssh command runs. It waits 5 seconds and then it tries to tail the first window (the one with the menu) and not the newly opened ssh window.
How do I change this? any help?
Thanks in advance

When you run the command start cmd /K ssh web the control is passed straight back to your menu script. (your sleep command, which BTW isn't a default command within cmd, is also run on the menu script)
You may need to either try concatenating your commands using & or instead call another script.
concatenation example:
#ECHO OFF
CLS
:MENU
ECHO.
ECHO 1 - tail - Error
ECHO 2 - tail - Access
ECHO -----------------------------
ECHO X - Close
CHOICE /C 12X /N /M "Select the action number."
IF ERRORLEVEL 3 GOTO :EOF
IF ERRORLEVEL 2 CALL :ACTION access
IF ERRORLEVEL 1 CALL :ACTION error
GOTO :EOF
:ACTION
ECHO.
START "" /WAIT CMD /C "ssh web & sleep 5 & tail -f /var/log/apache2/%1.log"
GOTO :MENU

you have to give all the commands to the new window:
start cmd /K "ping google.de & timeout 5"
& is to run one command after the other. See here for some more useful options: &&, ||)
(I used commands, that work on my computer to show the principle)
Note: cmd /k will keep the window open. Use cmd /c if you want it to close when finished.

Related

Batch File calling Console Application - Leaves CMD window open

I am calling a C# Console Application via batch file, in order to send the application output into a text file, with the date/time etc.
The problem I have is that when the console application completes, it leaves the batch window open, because there is a PAUSE (the C# equivalent), so a key must be pressed for the window to close. This means I do not know when the job has finished.
Is there a way I can make the CMD window close when the application finished, without having to change the C# Application code?
#ECHO================================================================================
#ECHO The Application is currently running and may take some time. Please wait...
#ECHO================================================================================
#ECHO OFF
C:\Applications\Job\Job.exe > C:\Applications\Job\Job_Output\"Output_%date:/=-% %time::=-%.txt"
Try this (note the collated dot after echo):
echo.| C:\Applications\Job\Job.exe > C:\Applications\Job\Job_Output\"Output_%date:/=-% %time::=-%.txt"
I have tried with pause and it works well:
echo.| pause
echo. is not echo. It just prints a newline, just what you need to trigger the pause.
Not sure whether will it work if your console app already have a Console.ReadLine() or Console.ReadKey() method but instead of just calling the *.exe use the Start command which will run the executable in a separate window like
start "MyConsoleTask" C:\Applications\Job\Job.exe > C:\Applications\Job\Job_Output\"Output_%date:/=-% %time::=-%.txt"
If you have not access to the console app source code, you may try a workaround
#echo off
#echo================================================================================
#echo The Application is currently running and may take some time. Please wait...
#echo================================================================================
set "timeStamp=%date:/=-%_%time::=-%
set "timeStamp=%timeStamp:~0,-3%" & rem remove ,centiseconds.
set "logFile=C:\Applications\Job\Job_Output\Output_%timeStamp%.txt"
rem start the exe in the same cmd window
start /B "" """C:\Applications\Job\Job.exe" > "%logFile%"""
rem wait for process startup
ping 1.1.1.1 -n 1 -w 750 >NUL
rem wait for logFile to be closed. This may flag that job.exe has ended
:wait
ping 1.1.1.1 -n 1 -w 50 >NUL & rem this avoids processor load
2>nul (>>"%logFile%" call )||goto :wait
rem send a key to the console. This may be captured by the exe file
set "_vbs_file_=%TEMP%\sendConsole.vbs"
(
echo/ set oWS ^= CreateObject^("wScript.Shell"^)
echo/ wScript.Sleep 50
echo/ oWS.SendKeys "{ENTER}"
)>"%_vbs_file_%"
if exist "%TEMP%\sendConsole.vbs" (set "_spawn_=%TEMP%\sendConsole.vbs") else (set "_spawn_=sendConsole.vbs")
ping 1.1.1.1 -n 1 -w 50 >NUL
start /B /WAIT cmd /C "cls & "%_spawn_%" & del /F /Q "%_spawn_%" 2>NUL"
#echo================================================================================
#echo Process completed. I guess...
#echo================================================================================
exit/B
so,
start /B ...
starts the job.exe executable in the same cmd window.
:wait
ping 1.1.1.1 -n 1 -w 50 >NUL & rem this avoids processor load
2>nul (>>"%logFile%" call )||goto :wait
waits until logfile is closed, so it may indicate that the previous proccess has ended.
set "_vbs_file_=%TEMP%\sendConsole.vbs"
(
echo/ set oWS ^= CreateObject^("wScript.Shell"^)
echo/ wScript.Sleep 50
echo/ oWS.SendKeys "{ENTER}"
)>"%_vbs_file_%"
if exist "%TEMP%\sendConsole.vbs" (set "_spawn_=%TEMP%\sendConsole.vbs") else (set "_spawn_=sendConsole.vbs")
ping 1.1.1.1 -n 1 -w 50 >NUL
start /B /WAIT cmd /C "cls & "%_spawn_%" & del /F /Q "%_spawn_%" 2>NUL"
send the enter key to the console, so the process waiting a keystroke may capture it.
NOTE: the ping wait trick works fine only if the IP is unreachable.
NOTE: the call and/or goto trick is discussed here
we gotta simulate a key press here, therefore we should toy with the keyboard buffer.
I am no Batch expert and this is the answer I found searching how to press keys with a batch:
#if (#CodeSection == #Batch) #then
#echo off
set SendKeys=CScript //nologo //E:JScript "%~F0"
rem Open the command here
start "" /B Job.exe > JobOutput.txt
rem sends the keys composing the string "I PRESSED " and the enter key
%SendKeys% "I PRESSED {ENTER}"
goto :EOF
#end
// JScript section
WScript.CreateObject("WScript.Shell").SendKeys(WScript.Arguments(0));
source:
Press Keyboard keys using a batch file
GnuWin32 openssl s_client conn to WebSphere MQ server not closing at EOF, hangs

start ping www.google.si closes my cmd window

I need to open cmd window multiple times from a cmd window. Site address or ip would change, so i can ping router, pc, google,.. The problem is when i issue this command it closes my original window i can open more than i window like that. I have set the cmd windows to go to a menu to choose other options after that. I do have some parameters set, but its not working with or without them.
start ping 192.168.0.1
If nothing else, could i open .bat file with this command and change address and parameters somehow?
try to use a bat file with this code
start cmd /k PING TARGET_IP1 -n 1 -w 5000 >NUL
start cmd /k PING TARGET_IP2 -n 1 -w 5000 >NUL
start cmd /k PING TARGET_IP3 -n 1 -w 5000 >NUL
/k stay the window open
>nul is like #echo off
-w 5000 is just the timeout in miliseconds
I solved it. Not really sure when i solved the original cmd window closing but here is the code:
start cmd /c "color 0a & title ping %ip% %l% %t% %n% & cls & ping %ip% %l% %t% %n% & echo. & pause >nul | set /p = Press any key to EXIT.."
I used /c to issue more commands in a row. Now i can open cmd windows without getting main one closed, use parameters i want each time and keep it opened after it finnishes its job.

How to close CMD when another program is exited?

I want to close a cmd window when the program csgo.exe is exited. There is one cmd window open, which is ( node server.js ) and I would like the program to be stopped when csgo.exe is quit.
Here is the full .bat.
#ECHO OFF
start steam://rungameid/730
start cmd /K "cd C:\CSGO-HUD-master & node server.js"
start cmd /K "cd C:\Program Files (x86)\Mozilla Firefox & start firefox.exe http://localhost:2626/ & exit"
Thanks!
The is doable if you know the task name of the program you want to watch. Here is the code:
#echo off
:LOOP
tasklist|findstr calc.exe > nul
if %errorlevel%==1 goto ENDLOOP
ping 127.0.0.1 -n 2 > nul
goto LOOP
:ENDLOOP
exit
In this example we want our bat to terminate after the calculator (calc.exe) is closed.
To achieve this, we first execute tasklist which gives us a list of all running programs. Then we check the output for the occurrence of calc.exe. If it is still running, findstr calc.exe will set %errorlevel% to 0 so we can just jump back and check again. If calc.exe is not running, %errorlevel% will be set to 1 so we know that we can jump out of the loop and terminate.
I've added the line ping 127.0.0.1 -n 2 > nul to avoid busy waiting. This line will make your code "wait" for one second between two iterations. Consider that to adjust the waiting time you'll have to replace 2 by the desired amount of seconds to wait +1. So if you want to wait for five seconds the code would be ping 127.0.0.1 -n 6 > nul.

How Can I Write a Batch File Where I Start one Program and When that Program Finishes or Closes, Start Another

For example:
#echo off
start C:\Windows\system32\dfrgui.exe /C
Wait for defragmentation to finish.
start C:\"Program Files (x86)"\CCleaner\CCleaner.exe /AUTO
Wait for CCleaner to finish.
start C:\Windows\system32\cleanmgr.exe /sagerun:1
and so on..
You get the point.
How I can do this?
Thanks.
Start can take a command line argument /WAIT e.g.
#echo off
title Test cmd start
start /WAIT wait.cmd 5
start /WAIT cmd /k echo launched second command
pause
This simple example uses another script I have written (wait.cmd shown below) as the first command executed, as you will see if you test this with the /WAIT option specified the script allows the first command to finish before continuing:
#echo off
rem call with # of seconds to wait
set /a secs=%1
set /a ms=%secs%*1000
echo Process will wait for %secs% seconds and then continue...
ping 1.1.1.1 -n 1 -w %ms% > nul
echo.
exit
As a side note if you open a cmd session you can find out about the arguments that a command such as start accepts e.g.
Update following comment
So to adapt the commands you listed in your question to finish before starting the next command in the script you could use:
#echo off
start /WAIT C:\Windows\system32\dfrgui.exe /C
start /WAIT C:\"Program Files (x86)"\CCleaner\CCleaner.exe /AUTO
start /WAIT C:\Windows\system32\cleanmgr.exe /sagerun:1

Batch Scripting: Command Not Running With If Statement

So for starters, I'm kind of a scrub coder and I'm enjoying playing around with batch scripting.
I don't like to have multiple command line windows open, so I'm trying to script everything into this 1 batch file, including the ability to run standard command line commands.
Here's the section of my code that I'm having issues with.
:three
echo.
echo ***************************
echo **Enhanced Command Prompt**
echo ***************************
:three.b
echo.
set /p Return=Enter Command:
if '%Return%'=='Return' goto home
cmd /c %Return%
goto three.b
NOTE: I've also removed cmd /c, and %Return% excutes with no issue, but for the sake personal preference, I've kept the cmd /c present.
The issue with this line of text, is executing a command such as "Ping Google.com" crashes the window. So does ipconfig /all, and anything else that doesn't seem to execute right away.
If I remove the "IF=Return", then I have no problems running ping google.com or anything else, but I'm ultimately trapped in this section of code without that IF statement.
The IF statement itself functions, but "Ping X" and other commands do not without crashing the batch file.
Any help would be appreciated.
Thanks!
You will need to use double quotes in if as this is the proper way of quoting/comparing strings in batch file.
:three
echo.
echo ***************************
echo **Enhanced Command Prompt**
echo ***************************
:three.b
echo.
set /p Return=Enter Command:
if "%Return%" == "Return" goto home
cmd /c %Return%
goto three.b

Resources