TheThankfulOne
TheThankfulOne

Reputation: 132

Cannot set a variable in a batch file

I have the following...

@ECHO OFF
setlocal EnableDelayedExpansion

for /f "skip=1" %%p in ('wmic cpu get loadpercentage') do @echo %%p
ECHO ...this worked
ECHO. 
PAUSE

for /f "skip=1" %%p in ('wmic cpu get loadpercentage') do set cpu=%%p
ECHO cpu is %cpu%
ECHO ...this did not work
ECHO. 
PAUSE

How come I can't set the number in the variable %cpu% it's always blank!

Upvotes: 2

Views: 290

Answers (2)

npocmaka
npocmaka

Reputation: 57252

for /f "skip=1" %%p in ('wmic cpu get loadpercentage') do set cpu=%%p & goto :end_for
:end_for

WMIC produces an empty line at the end.You can try also with /format:csv at the end of wmic call which will prevent that.

Check also this: http://www.dostips.com/forum/viewtopic.php?f=3&t=4266

Upvotes: 3

eiselems
eiselems

Reputation: 180

Have not found a solution quite yet but the problem seems to be that

wmic cpu get loadpercentage

has more than your two lines in the output, the for loop iterates over all lines

if i actually echo all sets in the for loop it looks like this

set cpu=1
set cpu=
cpu is 

Upvotes: 0

Related Questions