revlis.nl
Blog & Notes about OSS, OSes, devops, virtualization, programming (hobby) projects, security and tech news
March 3, 2017 — 12:55
Author: silver Category: windows Comments: Off
Check if a program if not already running before starting it in a Windows batch file.
Uses C:\Windows\System32\find.exe (findstr should work equally well).
Example:
tasklist /nh /fi "imagename eq explorer.exe" | find /i "explorer.exe" > nul || ( start "" C:\WINDOWS\explorer.exe )
Function:
:func_runImageTask tasklist /nh /fi "imagename eq %~1" | find /i "%~1" > nul || ( start "" "%~2" ) GOTO :EOF
Function using window titles:
:func_runTitleTask tasklist /v | find "%~1" > nul || ( start "" "%~2" ) GOTO :EOF
Call function:
CALL :func_runImageTask "Calculator.exe" "C:\WINDOWS\System32\calc.exe" CALL :func_runTitleTask "Calculator" "C:\WINDOWS\System32\calc.exe"
From:
This batch file takes program names (IMAGENAMES variable) or window titles (WINDOWTITLES and starts them if they are not already running. Programs can have arguments (e.g. outlook.exe).
ReOpen.bat
::
:: ReOpens programs which are not already running 20161220 slv
::
@echo off
setLocal EnableDelayedExpansion
::
:: Configure programs here making sure to use ,^ at eol for continuation
::
SET IMAGENAMES=^
"chrome.exe,C:\Program Files (x86)\Google\Chrome\Application\chrome.exe",^
"Xshell.exe,C:\Program Files (x86)\NetSarang\Xshell 5\Xshell.exe",^
"outlook.exe,C:\Program Files\Microsoft Office\Office14\OUTLOOK.EXE,/recycle"
FOR %%x in (%IMAGENAMES%) DO (
FOR /f "tokens=1-3 delims=," %%a in (%%x) do (
CALL :func_runImageTask "%%a" "%%b" "%%c"
)
)
SET WINDOWTITLES=^
"www@webserver,C:\Program Files (x86)\PuTTY\putty.exe,-load webserver",^
"user@debian,C:\Program Files (x86)\PuTTY\putty.exe,-load debian"
FOR %%x in (%WINDOWTITLES%) DO (
FOR /f "tokens=1-3 delims=," %%a in (%%x) DO (
CALL :func_runTitleTask "%%a" "%%b" "%%c"
)
)
GOTO :EOF
:func_runImageTask
tasklist /nh /fi "imagename eq %~1" | %windir%\system32\find.exe /i "%~1" > nul || ( start "" "%~2"^ %~3 )
GOTO :EOF
:func_runTitleTask
tasklist /v | %windir%\system32\find.exe "%~1" > nul || ( start "" "%~2"^ %~3 )
GOTO :EOF
::
:: Examples:
::
:: MANUAL: tasklist /nh /fi "imagename eq explorer.exe" | %windir%\system32\find.exe /i "explorer.exe" > nul || ( start "" C:\WINDOWS\explorer.exe C:\Users\%USERNAME%\Desktop )
:: FUNCTION: CALL :func_runImageTask "Calculator.exe" "C:\WINDOWS\System32\calc.exe"
::
