So I am trying to create a variable from the output of the below command in a batch file. It works fine at the command prompt where I get the process ID 1292:
C:\\Documents and Settings\\user\u0026gt;wmic process where (name="cmd.exe" and CommandLine like "%%%queue%%%") get ProcessID
Which Returns
ProcessId
1292
if I do this I get the return I need if only one instance is running:
for /f "tokens=*" %%f in ('wmic process get processid /value ^| find "="') do set "%%f"
echo processid is %processid%
However, I would like to use the multiple content combo because if I want to get the processID for an exe that is running multiple times, at least I can narrow it down.
Any suggestions would be appreciated.
Try with something like
@echo off
setlocal enableextensions disabledelayedexpansion
set "queue=testing"
for /f "tokens=2 delims==" %%a in ('
wmic process
where "name='cmd.exe' And commandLine like '%%%queue%%%'"
get ProcessID /value
') do echo %%a
or
@echo off
setlocal enableextensions disabledelayedexpansion
set "queue=testing"
for /f "tokens=2 delims==" %%a in ('
wmic process
where ^(
name^="cmd.exe"
and commandLine like "%%%queue%%%"
^)
get ProcessID /value
') do echo %%a
just two different samples of escaping the wmic
command inside the for /f
.
In the first case the where
conditions are wrapped in double quotes with values using single quotes. There is not need for escape characters as the double quotes will deal with it, but all the conditions must be on the same line.
In the second case the where
conditions are wrapped with parenthesis with values enclosed in double quotes. Some of the characters will need escape characters, but you have more options on how to write the command.
Note that these samples have a problem that probably will not affect you: both samples search for cmd
instances, and the wmic
command is started inside a separate cmd
instance (the way for /f
executes commands), and that instance will also match the condition (it includes the same substring in its own command line).
edited to adapt to comments
@echo off
setlocal enableextensions disabledelayedexpansion
set "queue=testing"
for /f "tokens=2 delims==" %%a in ('
wmic process
where ^(
name^="cmd.exe"
and commandLine like "%%%queue%%%"
and not commandLine like "%%[{%random%%random%%random%}]%%"
^)
get ProcessID /value 2^>nul
') do echo %%a
To avoid the inclusion of the cmd
instance created by the for /f
command that holds the wmic
command we only need to include an additional condition that will math this problematic instance (the condition will be in the command line of the cmd
instance) but that must not match the instance we are looking for.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.