For context, I found this among XAMPP batch files:
@echo off
SetLocal EnableDelayedExpansion
set "PID_LIST="
for /f "tokens=2" %%V in ('tasklist.exe ^| findstr /i "%1" 2^>NUL') do @set "PID_LIST=!PID_LIST! /PID %%V"
if defined PID_LIST (
taskkill.exe /F %PID_LIST%
) else (
echo Process %1 not running
)
SetLocal DisableDelayedExpansion
exit
I wish to write a single script to end all tasks related to my webserver. I have a basic understanding of batch, so I have been able to interpret most of what this script does:
- Delayed expansion is needed for the for loop
- The for loop gets the second token (
PID
) fromtasklist
and saves it into a variable, where the task is given by paramater1
. - If the task is found it is ended with
taskkill
Based on this I came so far:
@echo off
cd /D %~dp0
for /f "tokens=2" %%V in ('tasklist.exe ^| findstr /i "httpd.exe" 2^>NUL') do taskkill.exe /pid /f %%V
for /f "tokens=2" %%V in ('tasklist.exe ^| findstr /i "mysql" 2^>NUL') do taskkill.exe /pid /f %%V
:: etc
But I would ideally collapse this into one for loop. How could I add or
logic to the findstr
expression?
I also have a few questions, which I can’t find quick answers to anywhere. Can anyone answer these in the comments?
- In my script, do I need to
EnableDelayedExpansion
? - What is the purpose of
set "PID_LIST="
, leaving the variable undefined? - I don’t fully understand the command pipe
findstr
: what is the meaning of2^>NUL
, and why does>
need to be careted? - How does the
set
command append to the variable with!VARIABLE!
?