First post here, so apologies if I don\'t do this quite right.
I\'m trying to output the OS version on a remote Windows PC, but I keep getting unwanted data. Execut
I'd suggest
set "remotever="
FOR /F "skip=1 tokens=*" %%A in ('wmic /node:%hostname% OS get caption^|more') DO if not defined remotever set "remotever=%%A"
echo %remotever:~0,-1%
more
is the classic batch method to conver wmic
's unicode output to ANSI.
But there's a catch. Apart from Unicode, WMIC
"ends" its lines with CRCRLF not CRLF and the penultimate CR is then included in the value assigned to the variable (hence echo
the substring not including the last character - and you'll find some trailing spaces...).
(as a slightly easier demo, try echo q%%Aj
in your original - you'll find the q
is overwritten by the j
)
Hence, to capture the first line out, set
a variable to nothing, then in the for
loop set
it to the value you want to capture, but gate the set
with if not defined
.
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
@echo off
for /f "usebackq delims= skip=1" %%a in (`wmic OS get caption 2^>nul ^| findstr "."`) do set caption=%%a
for /f "usebackq delims=" %%a in (`echo %caption%`) do set caption=%%a
set "caption=%caption:~0,-1%"
echo Caption=[%caption%]
Pipe it to the find command.
@echo off
set /p hostname=PC hostname?
echo.
FOR /F "tokens=1,2 delims==" %%A in ('wmic /node:%hostname% OS get caption /value ^|find /I "caption"') DO echo %%B
echo.
pause