Parsing WMIC output

2019-09-03 05:30发布

I have a BAT script that is supposed to read the current screen resolution to variables. I get the screen resolution with the wmic desktopmonitor get screenwidth /value command (for the width, the height is the same thing).

Example output:

C:\Users\Pietu1998>wmic desktopmonitor get screenwidth /value


ScreenWidth=1920


ScreenWidth=




C:\Users\Pietu1998>

I have two monitors, so it only shows the resolution for the one in use.

I have tried using a for loop to skip the first two empty lines and then read the data.

set screenwidth=

for /F "skip=2 tokens=*" %%F in ('wmic desktopmonitor get screenwidth /value') do (
    if "%screenwidth%" equ "" (
        echo line: %%F
        set screenwidth=%%F
        echo var: %screenwidth%
        set screenwidth=%screenwidth:~12%
    )
)

I am getting the output correctly, because the lines are printed by the first echo, but for some reason the second echo outputs nothing. The line is not put in the variable.

What am I missing here? I've been googling about it for 2 hours now.

UPDATE: I found a way using findstr and a temporary file.

wmic desktopmonitor get screenwidth /value | findstr "ScreenWidth=." > %temp%\tmp
set /P screenwidth=< %temp%\tmp
del %temp%\tmp

1条回答
Lonely孤独者°
2楼-- · 2019-09-03 05:39

echo var: %screenwidth% <--- You can't set and use a variable within a loop without some special techniques, like delayed expansion.

Does this do what you need?

@echo off
set "screenwidth="
for /F "tokens=2 delims==" %%F in ('wmic desktopmonitor get screenwidth /value') do (
    if not defined screenwidth set screenwidth=%%F
)
pause
查看更多
登录 后发表回答