简体   繁体   中英

Get the result of a WMIC command and store it in a variable

I have seen some batch scripts working that way, including all around stackoverflow.

My question is simple: Why the MEM part isn't working?

@echo OFF

SET CPU="$CPU"

echo CPU: %NUMBER_OF_PROCESSORS%

FOR /F "delims=" %%i IN ('wmic computersystem get TotalPhysicalMemory') DO set MEM=%%i

echo MEM: %MEM%

You can do something like that with formatting the output of WMIC with For / Do loop like that :

@echo off
Call :GetTotalPhysicalMemory
echo TotalPhysicalMemory = %MEM% & pause
exit
::***********************************************
:GetTotalPhysicalMemory
for /f "tokens=2 delims==" %%a in ('
    wmic computersystem get TotalPhysicalMemory /value
') do for /f "delims=" %%b in ("%%a") do (
    Set "MEM=%%b" 
)
exit /b
::***********************************************

That's simple. wmic computersystem get TotalPhysicalMemory outputs three lines of text:

TotalPhysicalMemory
12867309568
<blank line>

So your for-loop does three iteration. In the first one MEM is set to TotalPhysicalMemory , in the second one it's set to 12867309568 and finally it becomes . So your output is empty.

This is quite ugly but will solve your problem:

@echo OFF
setlocal enabledelayedexpansion
SET CPU="$CPU"
echo CPU: %NUMBER_OF_PROCESSORS%
FOR /F "delims= skip=1" %%i IN ('wmic computersystem get TotalPhysicalMemory') DO (
    set MEM=%%i
    goto STOP

)
:STOP
echo MEM: !MEM!

skip=1 will ignore TotalPhysicalMemory and goto STOP will break the loop after the first iteration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM