2

I'm trying to process the output of the command wmic os get version in a cmd.exe batch for loop. Seems simple enough:

for /f %%G in ('wmic os get version') do (
    echo %%G
)

But the output is:

Version
10.0.19044
ECHO is off.

That last line, ECHO is off. means that the %%G was "blank".

Ok so no problem, just test for that:

for /f %%G in ('wmic os get version') do (
    if [%%G] neq [] echo %%G
)

Output is the same:

Version
10.0.19044
ECHO is off.

So is it not blank? After much experimentation, it contains a single carriage return character aka <CR> aka 0x0D aka \r (not to be confused with line feed aka <LF> aka 0x0A aka \n; also note that <CR><LF> pair is the standard windows/dos line terminator), as this code demonstrates:

for /f %%G in ('wmic os get version') do (
    echo /////////%%G\123\
)

Output:

/////////Version\123\
/////////10.0.19044\123\
\123\////

So the question is, how to detect/process that last line with the carriage return. Can I detect it with an if comparator? Can I string substitute it? Can I use some for delimiter? What can I do? My immediate need is to just not print that last line for neatness, but one can imagine any arbitrary processing wanted on the text, including for /f with tokens and other delims.

john v kumpf
  • 431
  • 3
  • 8
  • Another method I like to use is the `format:csv` option. In other words, `for /f "tokens=2 delims=," %%g in ('%__APPDIR__%wbem\WMIC.exe os get version /Format:csv') do set "_version=%%g" echo %_version%` – Qwerty Jul 14 '22 at 12:17

1 Answers1

2

The output of WMIC is unicode !

The trailing <CR> can be removed by passing the value through another FOR /F loop.

This also removes the phantom "blank" line (actually a <CR>)

@echo off
Title Removing the trailing ^<CR^> by passing the value through another FOR /F
set "Version="
@for /f "delims=" %%a in ('"wmic os get version /Value"') do (
    @for /f "delims=" %%b in ("%%a") do if not defined Version set %%b
)
echo OS Version : [%Version%]
pause

EDIT: Refer to this good answer here wmic output to file without addtional line issue and here too from @Compo; You can also in your case change the output format of : /Format:MOF


@echo off
Title Change the output of WMIC into MOF
@For /F Tokens^=6Delims^=^" %%A In ('"WMIC OS Get Version /Format:MOF"') Do Echo OS Version : [%%A]
pause
Hackoo
  • 18,337
  • 3
  • 40
  • 70