I'd like to read the current monitor resolution and set an environment variable. This works in WinXP, but not in Vista because wmic adds a newline at the end:

FOR /F %%L IN ('wmic desktopmonitor get screenheight') DO set YRES=%%L

Adding a test does not work as expected:

FOR /F %%L IN ('wmic desktopmonitor get screenheight') DO if not [%%L]==[] set YRES=%%L

2 Answers 2


Thanks to Ben Nesson answer i've found an easy solution that works both on XP and Vista: just pipe wmic output to findstr and strip all the newlines:

FOR /F %%L IN ('wmic desktopmonitor get screenheight ^| findstr "."') DO set YRES=%%L

Oh, that extra carriage return does some weird stuff.

tl;dr: Something like this seems to work:

FOR /F %%L in ('wmic desktopmonitor get screenheight') DO (
  CALL :foo "%%L"
:: ...

  IF NOT [%~1]==[] set RESULT=%~1

Anyway, the root of the problem, as you've noted, is wmic weirdly outputting those extra carriage returns. (It also throws in some spaces for good measure, but without "delims=" or something, those get thrown out by the for loop.) Ordinarily, FOR will just ignore blank lines, but for some reason, instead of the standard "\r\n" newline, wmic spits out "\r\r\n". And I guess FOR doesn't handle that sensibly.

Matter of fact, cmd in general doesn't handle that sensibly. I tried setting %%L to a temp variable and checking the temp variable with EnableDelayedExpansion, but it didn't work reliably; it seems that %var% will discard carriage returns, while !var! retains them. Go ahead, try and guess what output you'll get from this:

@ echo off
setlocal EnableDelayedExpansion
for /f %%a in ('wmic desktopmonitor get status') DO (
  set t=%%a
  set bang=!t!
set doodle=%t%
set bangbang=!bang!
set bangdoodle=%bang%

ECHO [%doodle%]
ECHO [!doodle!]
ECHO [%bang%]
ECHO [!bang!]
ECHO [%bangbang%]
ECHO [!bangbang!]
ECHO [%bangdoodle%]
ECHO [!bangdoodle!]

So thanks, you've given me a new weird thing to try to figure out in lieu of doing actual work!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.