Parsing WMIC output

荒凉一梦 提交于 2020-01-06 07:05:40

问题


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:


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


来源:https://stackoverflow.com/questions/23724982/parsing-wmic-output

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!