For /F with wmic unwanted output

Magoo identified the source of the problem – the conversion of WMIC unicode output to ANSI is flawed in that each line ends with CRCRLF instead of the normal CRLF.

FOR /F breaks at (and strips) each LF, leaving CRCR. FOR /F strips the last character from each line if and only if it happens to be a CR, so that leaves one CR at the end of every line. FOR /F ignores empty lines, but CR is not an empty line, hence the unwanted Echo is off. output.

Magoo and Squashman have provided workable solutions to your problem, but they are not generic solutions that apply to all FOR /F – WMIC situations. A common issue arises when FOR /F output is stored in variables – the unwanted CR is often at the end of the value, which can cause problems later on.

We can use the known mechanics of FOR /F to strip the unwanted CR from every line by simply adding an extra FOR /F.

So the generic template that always works looks like

for delims^=^ eol^= %%. in ('wmic ....') do for /f "whatever options you need" %%A in ("%%.") do ...

or if you need to skip N lines, then

for skip^=N^ delims^=^ eol^= %%. in ('wmic ....') do for /f "whatever options you need" %%A in ("%%.") do ...

The arcane syntax in the first FOR /F sets both DELIMS and EOL to nothing. If you know that none of your output begins with ;, then you can simply use "delims=", or "skip=N delims=". This is the case in your situation.

So the solution becomes:

for /f "skip=1 delims=" %%. in ('wmic /node:%hostname% OS get caption') do for /f "delims=" %%A in ("%%.") do echo %%A

Leave a Comment