Re-opening files in Batch - windows

For definitely not malicious reasons, I need to have a batch file always open.
I have some base code:
:b
echo off
tasklist /fi "imagename eq cmd.exe" |find ":" > nul
if errorlevel 1 taskkill /f /im "game.bat"&start game.bat
goto b
And it works fine if want notepad.exe or blah.txt and etc.
Except for batch files, as the program itself is a batch file,
the system sees cmd.exe is already open.

It works except for batch files, as the system sees cmd.exe is already open.
Give your batch file a Title by adding the following command to game.bat:
title %~nx0
Check if game.bat is running by using tasklist with /v option:
:b
#echo off
tasklist /v | find "game.bat" > nul
rem errorlevel 1 means game.bat is not running, so start it
if errorlevel 1 start game.bat
rem timeout to avoid excessive processor load
timeout 60
goto b
Further Reading
An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
tasklist - TaskList displays all running applications and services with their Process ID (PID) This can be run on either a local or a remote computer.
timeout - Delay execution for a few seconds or minutes, for use within a batch file.
title - Change the title displayed above the CMD window.

Related

Batch to check if process exists

I'd like a batch that will check if the process firefox.exe exists (after it has been started by the start command).
If the process exists, it will go to the label :fullscreen,
else the batch will go the the label :timeout. Then, it will check again if the process firefox.exe exists and if not, it will go again to the label :fullscreen until the process exists.
Here is my batch:
#echo off
start "C:\Program Files (x86)\Mozilla Firefox\firefox.exe"
:timeout
timeout /t 5
:fullscreen
nircmd sendkeypress F11
exit
How can I do this check ?
You can also use QUERY PROCESS:
#Echo Off
If Not Exist "%ProgramFiles(x86)%\Mozilla Firefox\firefox.exe" Exit/B
Start "" "%ProgramFiles(x86)%\Mozilla Firefox\firefox.exe"
:Loop
Timeout 5 /NoBreak>Nul
QProcess firefox.exe>Nul 2>&1||GoTo :Loop
NirCmd SendKeyPress F11
I suggest for this task the batch file:
#echo off
start "" /max firefox.exe
if errorlevel 1 goto :EOF
set LoopCount=0
:WaitLoop
%SystemRoot%\System32\timeout.exe /T 5
%SystemRoot%\System32\tasklist.exe /FI "IMAGENAME eq firefox.exe" 2>nul | %SystemRoot%\System32\find.exe /I "firefox.exe" >nul
if not errorlevel 1 nircmd.exe sendkeypress F11 & goto :EOF
set /A LoopCount+=1
if not %LoopCount% == 6 goto WaitLoop
Let me explain the few command lines used here.
1. Starting Firefox
The command START being an internal command of cmd.exe interprets the first double quoted string as optional title for the console window. Therefore the command line
start "C:\Program Files (x86)\Mozilla Firefox\firefox.exe"
results just in opening a new console window with the window title:
C:\Program Files (x86)\Mozilla Firefox\firefox.exe
For that reason "" is specified as first START argument to define an empty title. Firefox is a GUI application. So no console window is opened which means an empty window title is really enough.
The parameter /max would not be really necessary, but the goal is to get Firefox into full screen mode after starting. So why not starting it already maximized?
32-bit version of Firefox is by default installed in directory %ProgramFiles% on 32-bit Windows and in %ProgramFiles(x86)% on 64-bit Windows. But it is possible during the installation to install Firefox into any other folder. But Firefox installer is well coded and registers firefox.exe in Windows registry under key:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths
This is recommended by Microsoft as written in MSDN article Application Registration.
The command START searches also in Windows registry under this key for an executable specified as argument without path as explained in answer on Where is “START” searching for executables?
This is the reason for using just firefox.exe on START command line because that starts an installed Firefox independent on installation location.
START displays an appropriate message box if firefox.exe could not be started and exits in this case with a return code greater 0 (9059 in my test on one computer).
The help output on running if /? in a command prompt window explains how to evaluate the exit code of a previous command or application without usage of immediate or delayed environment variable expansion and therefore working anywhere in a batch file from MS-DOS (really!) to currently latest Windows 10.
The command line if errorlevel 1 goto :EOF means IF start failed to start firefox.exe indicated by an exit code greater or equal 1 THEN exit execution of this batch file. For details on exiting batch file execution see answer on Where does GOTO :EOF return to?
2. Checking for running Firefox
The command TASKLIST being an external command, i.e. a console application in system directory of Windows, outputs a list of running processes. This list can be already filtered by TASKLIST itself for a specific process as done in batch file with /FI "IMAGENAME eq firefox.exe".
But TASKLIST is designed for just printing a list of processes. It is not designed for checking if a specific process is running and returning the result to the calling process via exit code. TASKLIST always exits with 0.
But an error message is output to handle STDERR on using a filter and no process can be found in process list matching this filter. For that reason 2>nul is used to suppress this error message by redirecting it to device NUL. Read the Microsoft article about Using Command Redirection Operators for more information about redirection.
A simple method to get a simple false/true respectively 0/1 result on checking for running Firefox is filtering output of TASKLIST with external command FIND which exits with 0 if the string to find was indeed found or with 1 if the searched string could not be found in the text read in this case from STDIN. The output of FIND is of no interest and therefore suppressed with redirection to device NUL using >nul.
Instead of using TASKLIST and FIND it is also possible to use QPROCESS:
%SystemRoot%\System32\qprocess.exe firefox.exe >nul 2>&1
QPROCESS exits with exit code 1 if firefox.exe could not be found in list of running processes. Otherwise the exit code is 0 on firefox.exe is running.
3. Evaluating Firefox process checking result
if not errorlevel 1 nircmd.exe sendkeypress F11 & goto :EOF
The IF command checks if exit code of FIND is NOT greater or equal 1 which means if exit code is lower than 1. Command FIND exits never with a negative value. So if this condition is true then it is time to execute nircmd.exe to send key press F11 to application in foreground hopefully being Firefox (not guaranteed by this code) and exit batch file processing.
Otherwise the batch file should wait once again 5 seconds and then do the check again. This can very easily result in an endless running batch file in case of started Firefox is immediately closed by the user before the 5 seconds wait timed out. For that reason it is counted how often the wait loop is already executed. After 6 loop runs, or 30 seconds, it is really time to no longer wait for Firefox and exit the batch file.
4. Getting more information about used commands
For understanding the used commands and how they work, open a command prompt window, execute there the following commands, and read entirely all help pages displayed for each command very carefully.
echo /?
find /?
if /?
qprocess /?
set /?
start /?
tasklist /?
timeout /?
And Single line with multiple commands using Windows batch file should be also read explaining operator & in addition to all other web pages referenced already above.
You can show a list of opened programs like this:
tasklist
To check if firefox exists:
EDIT: Code edited to show a fully working example
#echo off
start "C:\Program Files (x86)\Mozilla Firefox\firefox.exe"
goto :checkloop
:checkloop
tasklist|find "firefox.exe" > NUL
if %ERRORLEVEL% == 0 (
call :fullscreen
exit
) else (
call :timeout
goto :checkloop
)
:fullscreen
nircmd sendkeypress F11
goto :EOF
:timeout
timeout /t 5
goto :EOF

CMD command not running in batch file

I am trying to create a batch file that runs a command.
The first part of the command checks to see if a particularly named window is open on my desktop. If it is it then closes that window (by sending a command to the program with the window open - Virtual Audio Cable).
#For /f "Delims=:" %A in ('tasklist /nh /v /fi "WINDOWTITLE eq Headphones"') do #if %A==INFO (echo Prog not running) else (start /min "audiorepeater_ks" "c:program files\Virtual Audio Cable\audiorepeater_ks.exe" /CloseInstance: Headphones)
Now this command seems to work fine when I execute it via the command line.
But it does nothing when I try to put it in a batch file
I have tried a .bat file and a .cmd file and also created a shortcut to the .cmd file where i have prepended the target field in properties with "C:\Windows\System32\cmd.exe /c"
Any ideas on how I can get this to run via batch?
You will have to escape "%A" with "%%A" as CristiFati pointed out. For more escape characters, please visit https://www.robvanderwoude.com/escapechars.php

Need a batch file to start, delay a close, and restart another batch file.

I have searched and searched and this is the closest code I have found:
#echo off
:loop
C:\CryptoCurrency\nexus_cpuminer\start.bat
timeout /t 30 >null
taskkill /f /im nexus_cpuminer.exe >nul
goto loop
A few things: notice the start.bat. The .exe I need to launch has to start via the .bat file because the .bat file contains information the .exe needs.
Secondly, the .exe launches a CMD prompt window which shows me what's going on.
(keep this in mind because this is not your normal .exe, I WANT that CMD prompt window to close when it's KILLED)
I am aware I have it set for 30 seconds. I'm just testing right now. I'd like to set it for 4 hours before the kill command is called. Also, I'd like to set a "delay" of 30 seconds before the whole process starts over. I am running Windows 7 x 64.
You must change the name of the second Batch file to other name (i.e. starter.bat) and execute it via the start internal command in order to execute it in parallel:
#echo off
:loop
start "" cmd /C "C:\CryptoCurrency\nexus_cpuminer\starter.bat"
timeout /t 30 >null
taskkill /f /im nexus_cpuminer.exe >nul
goto loop
The last line in starter.bat file must be the execution of nexus_cpuminer.exe, so when it is killed via taskkill, the .bat file ends immediately.
Another simpler approach is to directly execute nexus_cpuminer.exe in this Batch file, via start "" cmd /C nexus_cpuminer.exe command, so this process be opened in its own cmd.exe window.
If you CALL start.bat, it will return to your 'calling' script.
If you give start.bat a TITLE, you can /FIlter your TASKKILL command to EQ that WINDOWTITLE

Wait for a .bat file to close within a windows batch file

I need to create a windows batch file (*.bat) file that only runs its commands if certain processes (and batch files) are NOT running.
I have looked at a solution that works for processes (*.exe) here:
How to wait for a process to terminate to execute another process in batch file
I want to do something very similar, however, there is one difficulty: Batch files show up as "cmd.exe" in the "TASKLIST" command.
I want to check if a specific bat file is running, for example: "C:\mybatch.bat", and if it is, wait until it is closed.
Checking if a specific bat file mybatch.bat is running could be a tougher task than it could look at first sight.
Looking for a particular window title in tasklist /V as well as testing CommandLine property in wmic process where "name='cmd.exe'" get CommandLine might fail under some imaginable circumstance.
1st. Can you
add title ThisIsDistinguishingString command at beginning of the mybatch.bat and
remove all other title commands from mybatch.bat and
ensure that mybatch.bat does not call another batch script(s) containing a title command?
Then check errorlevel returned from find command as follows:
:testMybatch
tasklist /V /FI "imagename eq cmd.exe" | find "ThisIsDistinguishingString" > nul
if errorlevel 1 (
rem echo mybatch.bat batch not found
) else (
echo mybatch.bat is running %date% %time%
timeout /T 10 /NOBREAK >NUL 2>&1
goto :testMybatch
)
2nd. Otherwise, check if wmic Windows Management Instrumentation command output could help
wmic process where "name='cmd.exe'" get /value
Then you could detect mybatch.bat in its output narrowed to
wmic process where "name='cmd.exe'" get CommandLine, ProcessID
Note that wmic could return some Win32_Process class properties, particularly CommandLine, empty if a particular process was launched under another user account or elevated (run as administrator).
Elevated wmic returns all properties in full.
What you say happens by default.
To test, crate a new .bat file (let's say 1.bat) and put in it
calc
mspaint
Save and run it.
Calculator will start. You will notice that Paitbrush will launch only when you have closed calculator.

Batch file to uninstall a program

I'm trying to uninstall a program EXE via batch file and am not having any success.
The uninstall string found in the registry is as follows:
C:\PROGRA~1\Kofax\Capture\ACUnInst.exe /Workstation
C:\PROGRA~1\Kofax\Capture\UNWISE.EXE /U
C:\PROGRA~1\Kofax\Capture\INSTALL.LOG
If I run that from CMD or batch it does nothing.
If I run C:\PROGRA~1\Kofax\Capture\UNWISE.EXE /U from CMD it will open up a dialog box to point to the INSTALL.LOG file and then proceed to uninstall.
At the end, it will ask me to click finish.
I need this to be silent, can you point me in the right direction? This is on XP and 7.
Every program that properly installs itself according to Microsoft's guidelines makes a registry entry in either HKLM\Software\Microsoft\Windows\CurrentVersion\Uninstall (for machine installs) or HKCU\Software\Microsoft\Windows\CurrentVersion\Uninstall (for user profile installs). Usually, the key for the program will be its GUID, or else the name of the program. Within that key will be an entry called UninstallString. This contains the command to execute to uninstall the program.
If you already know ahead of time what you will be uninstalling, it should be easy enough to just put that in your batch file. It gets tricky when you try to automate that process though. You can use the reg command to get data from the registry, but it returns a lot of text around the actual value of a given key, making it hard to use. You may want to experiment with using VBscript or PowerShell, as they have better options for getting data from the registry into a variable.
This might help you further.....
How to Create a script via batch file that will uninstall a program if it was installed on windows 7 64-bit or 32-bit
I've had the same problem and this is what I came up with.
Before you start using this method though, you might wanna look up the name of the application on WMIC using CMD so..
First you wanna do: WMIC product > C:\Users\"currentuser"\Desktop\allapps.txt
I'd recommend to output the command to an TXT file because it's really confusing to read it in the Cmd prompt, plus is easier to find the data you are looking for.
Now what you wanna do is find the actual name of the app... If you look at the code I put in, the app name says SkypeT because skype has "™" in the end of it and the command prompt can't interpretate that as it is.
After you got the app name, just put in the find in the 4th line and substitute, a few lines which contain my examples with skype...
Also you can probably creat a variable called %APP% and not worry as much, but at it's current it works just fine...
One thing to note! with me the msi /quiet command did not work, the program would not install or uninstall so I used /passive, which lets the users see what's going on.
#Echo off
CD %cd%
:VerInstall
for /f "tokens=12,*" %%a in ('wmic product list system ^| Find /I "SkypeT"') do (
if Errorlevel = 0 (
Echo Skype is installed! )
if Errorlevel = 1 ( Echo Skype is not installed, proceding to the installation!
Ping localhost -n 7 >nul
goto :Reinstall )
)
:Status
tasklist /nh /fi "IMAGENAME eq "APP.exe" | find ":"> nul
if errorlevel = 1 goto :force
goto :Uninstall
:Force
echo We are killing the proccess... Please do not use the application during this process!
Ping localhost -n 7 > nul
taskkill /F /FI "STATUS eq RUNNING" /IM APP* /T
echo The task was killed with success! Uninstalling...
Ping localhost -n 7 > nul
:Uninstall
cls
for /f "tokens=12,*" %%a in ('wmic product list system ^| Find /I "SkypeT"') do (
set %%a=%%a: =%
msiexec.exe /x %%a /passive /norestart
)
:DoWhile
cls
Tasklist /fi "IMAGENAME eq msi*" /fi "STATUS eq RUNNING" | Find ":" >nul
if errorlevel = 1 (
echo Installation in progress
Goto :DoWhile
)
echo Skype is Uninstalled
:Reinstall
msiexec.exe /i SkypeSetup.msi /passive /norestart
:reinstallLoop
Tasklist /fi "IMAGENAME eq msi*" /fi "STATUS eq RUNNING" | Find ":" >nul
if errorlevel = 1 (
echo Installation in progress
goto :reinstallLoop
)
echo Skype is installed
:end
cls
color 0A
Echo Done!
exit
One last thing. I used this as an Invisible EXE task, so the user couldn't interact with the command prompt and eventually close the window (I know, I know, it makes the whole echoes stupid, but it was for testing purposes).for that I used BAT to EXE converter 2.3.1, you can put everything to work on the background and it will work very nicelly. if you want to show progress to users just write START Echo "info" and replace the info with whatever you want, it will open another prompt and show the info you need.
Remember, Wmic commands sometimes take up to 20 seconds to execute since it's querying the conputer's system, so it might look like it's doing nothing at first but it will run! ;)
Good luck :)
We needed a batch file to remove a program and we couldn't use programmatic access to the registry.
For us, we needed to remove a custom MSI with a unique name. This only works for installers that use msi or integrate such that their cached installer is placed in the Package_Cache folder. It also requires a unique, known name for the msi or exe. That said, it is useful for those cases.
dir/s/b/x "c:\programdata\packag~1\your-installer.msi" > removeIt.bat
set /p RemoveIt=< removeIt.bat
echo ^"%RemoveIt%^" /quiet /uninstall > removeIt.bat
removeIt.bat
This works by writing all paths for 'your-installer.msi' to the new file 'removeIt.bat'
It then assigns the first line of that bat file to the variable 'RemoveIt'
Next, it creates a new 'removeIt.bat' that contains the path/name of the .msi to remove along with the needed switches to do so.
Finally, it runs the batch file which executes the command to uninstall the msi. This could be done with an .exe as well.
You will probably want to place the 'removeIt.bat' file into a known writable location, for us that was the temp folder.

Resources