Page 1 of 1

Why for loop wmic get processid return an extra invalid value?

Posted: 21 Dec 2023 03:30
by PiotrMP006
Hi

Why for loop wmic get processid return an extra invalid value?

Code: Select all

for /f "usebackq skip=1 delims=" %%a in (`wmic process where "name='cmd.exe' and commandline like '%%%~n0%%'" get processid 2^>nul`) do echo %%a
The first returned value %%a is the real processid
The second returned value %%a is a non-existent processid

Why??????????????

Please help

Re: Why for loop wmic get processid return an extra invalid value?

Posted: 21 Dec 2023 11:17
by miskox
Looks like wmic returns an extra empty line and this is what you get.

Saso

Re: Why for loop wmic get processid return an extra invalid value?

Posted: 21 Dec 2023 11:42
by npocmaka_
I think I saw you asking the same question in SO and suggested in a comment to check this thread:-> viewtopic.php?t=4266

wmic sets an extra CR at the end which messes the output. But can be stripped with additional for loop:

Code: Select all

for /f "usebackq skip=1 delims=" %%a in (
  `wmic process where "name='cmd.exe' and commandline like '%%%~n0%%'" get processid 2^>nul`
) do (
  for %%# in ("%%a") echo %%#
) 

Re: Why for loop wmic get processid return an extra invalid value?

Posted: 22 Dec 2023 08:45
by Batcher

Code: Select all

@echo off
for /f "tokens=2 delims==" %%a in ('wmic process where "name='cmd.exe' and commandline like '%%%~n0%%'" get processid /value 2^>nul ^| find "="') do (
    call set "MyStr=%%%%a"
)
echo --%MyStr%--
pause