In a Windows batch file, I needed to set a variable to be the output of a command. You can use the
for
command for that purpose as
shown below. In the example below, I wanted to count the number of
hpboid.exe
processes running on a system.
REM Count the number of hpboid.exe processes running.
for /f "delims=" %%a in ('tasklist /fi "imagename eq hpboid.exe" ^| find /c /i "hpboid.exe"') do set numprocesses=%%a
echo Number of hpboid.exe processes running: %numprocesses% >> %log%
The tasklist /fi "imagename eq hpboid.exe"
command uses
the tasklist
command with the /fi
option to filter
the output of running processes to just those named hpboid.exe
.
I then want to "pipe" the output to the find
command. I use
the /i
option to have find
ignore the case of the
letters in hpboid.exe
, i.e., I want to count a process whether it
is named hpboid.exe
or HPBOID.exe
, etc. I use the
/c
option to tell find
to display only the count of
lines containing the string hpboid.exe
.
For Windows, and I presume DOS as well, you
need to put a caret, i.e., a ^
in front of the pipe character,
|
character to "escape" how it would otherwise be interpreted.
The variable numprocesses
is set to be the count of the
hpboid.exe
processes running, which I then send to a log file,
i.e., %log%
, which is a variable that was set earlier in the
batch file.
References:
-
Escaping a Character in a Windows Batch File
Date: July 12, 2010
MoonPoint Support -
Escape Characters
Date: January 17, 2008
Batcheero -
Escape character
Wikipedia, the free encyclopedia