glen morse
glen morse

Reputation: 63

if statement not working when the variable does have a value

So in this code !msp! in the echo outputs 0.

I am doing a check to see what that number is and then echo out the type. But for some reason its saying none of the if statements are true?

set msp=
for /f "tokens=2 delims==" %%f in ('wmic memorychip get memorytype /value ^| find "="') do (set msp=%%f)
echo !msp!
if !msp!=="0" ( 
echo Unknown s
)

if !msp!==0 ( 
echo Unknown n
)

The s and n is just me trying to see if " " matter.

Upvotes: 0

Views: 17

Answers (1)

Stephan
Stephan

Reputation: 56180

"0" is not equal to 0. Quote both sides of the equation. But that alone does not solve your problem. Wmic returns an ugly line ending of CRCRLF instead of just CRLF. The additional CR gets part of the variable (try echo a!msp!b with your code). One way (actually the most reliable) to solve that, is with another for:

setlocal enabledelayedexpansion
set "msp="
for /f "tokens=2 delims==" %%f in ('wmic memorychip get memorytype /value ^| findstr "="') do for %%g in (%%f) do set "msp=%%g"
echo !msp!
if "!msp!" == "0" ( 
  echo Unknown s
)
if !msp! == 0 ( 
  echo Unknown n
)

In this special case (output is a number), also set /a works:

for /f "tokens=2 delims==" %%f in ('wmic memorychip get memorytype /value ^| findstr "="') do set /a msp=%%f

Upvotes: 1

Related Questions