WMIC and FOR /F : A fix for the trailing <CR> problem
Posted: 01 Feb 2013 19:49
Somewhere on DosTips is at least one thread that talks about problems processing WMIC output with FOR /F. The problem stems from the fact that WMIC produces unicode output. Normally, FOR /F cannot handle unicode output. But somehow FOR /F processes the output of WMIC and converts it to ASCII. But there is an odd side effect that causes each parsed line to have an unwanted trailing <CR> character. Normally FOR /F does not preserve empty lines. But now the empty lines are no longer empty since they have a trailing <CR>.
The unwanted trailing <CR> can create complications when trying to parse the output.
I believe there are other commands like WMIC that have the same problem. For example, PING on XP.
Here is a demonstration of the <CR> problem
The trailing <CR> causes the cursor to reset to the beginning of the line and then the [ is overwritten by the ].
Each line actually ended with <CR><CR><LF>. FOR /F breaks at <LF> and strips off the last remaining character if it happens to be a <CR>. But it only strips a single <CR>, hence the problem with the unwanted trailing <CR> on each line.
Just today it dawned on me that there is a really simple solution - Simply pass the line through another FOR /F
Much better
Dave Benham
The unwanted trailing <CR> can create complications when trying to parse the output.
I believe there are other commands like WMIC that have the same problem. For example, PING on XP.
Here is a demonstration of the <CR> problem
Code: Select all
C:\test>for /f "delims=" %A in ('wmic os get localDateTime') do @echo [%A]
]LocalDateTime
]20130201203753.938000-300
]
The trailing <CR> causes the cursor to reset to the beginning of the line and then the [ is overwritten by the ].
Each line actually ended with <CR><CR><LF>. FOR /F breaks at <LF> and strips off the last remaining character if it happens to be a <CR>. But it only strips a single <CR>, hence the problem with the unwanted trailing <CR> on each line.
Just today it dawned on me that there is a really simple solution - Simply pass the line through another FOR /F
Code: Select all
C:\test>for /f "delims=" %A in ('wmic os get localDateTime') do @for /f "delims=" %B in ("%A") do @echo [%B]
[LocalDateTime ]
[20130201204419.057000-300 ]
Much better
Dave Benham