Reputation: 61
Here is an example of a batch file fragment:
@echo off
for /f "tokens=1" %%a in ('wmic process where "Caption = 'notepad++.exe'" get Processid ^| findstr /r "[0-9]"') do (
set procid=%%a
)
echo Notepad++ process ID is %procid%
pause
In it I get process ID for Notepad++ using WMIC
, extract the actual number using findstr
and then using FOR /F
command to set the result as a variable for further use. Maybe not the most elegant way, but it works for me.
When Notepad++ is running and WIMC finds its process, this works perfectly fine and I get result like this:
Notepad++ process ID is 222648
Press any key to continue . . .
However if Notepad++ isn't running, result looks like this:
No Instance(s) Available.
Notepad++ process ID is
Press any key to continue . . .
This No Instance(s) Available.
part is the message from WMIC and it's what bugs me. I would like it to not be printed on a screen.
When using command by itself in the Command Prompt I can suppress this message by adding 2>&1
at the end of WMIC part like this:
wmic process where "Caption = 'notepad++.exe'" get Processid 2>&1 | findstr /r "[0-9]"
However when I'm trying to do similar thing in a batch file like this:
@echo off
for /f "tokens=1" %%a in ('wmic process where "Caption = 'notepad++.exe'" get Processid 2>&1 ^| findstr /r "[0-9]"') do (
set procid=%%a
)
echo Notepad++ process ID is %procid%
pause
Batch file just crashes.
What am I doing wrong here? What will de the right way to suppress WMIC output in this case?
Thanks.
Upvotes: 1
Views: 797
Reputation: 61
Thanks to @Squashman and @Compo suggestions I was able to fix the crash and tidy up the whole thing a little bit. The final variant for now is as follows:
@echo off
for /f "tokens=2 delims==" %%a in ('wmic process where "Caption = 'notepad++.exe'" get Processid /value 2^>NUL') do (
set procid=%%a
)
echo Notepad++ process ID is %procid%
pause
2>&1
have been changed to 2^>NUL
(>
is escaped by ^
), also thanks to the /value
switch for WMIC
its output now can be parsed directly by FOR /F
without need for findstr
Upvotes: 3