StarsLikeDust
StarsLikeDust

Reputation: 3

Redirect output of batch command to an if statement (and string error?)

After a bit of research I've found what looks to be a good work around for getting the output of a batch command and setting it to a variable. I've used a bit of example code from a blog: Just Geeks to start. My eventual goal is to detect the model of computer the script is run on and do something based on which model. After a bit of modification I have:

FOR /F "tokens=* skip=1 delims=" %%A in ('wmic csproduct get name') do ( 
if %%A == "Vostro 430" goto vostro430
if %%A == "Optiplex 380" goto optiplex380
)
exit

:vostro430
REM do some stuff here

:optiplex380
REM do some stuff here

Its useful to note that wmic csproduct get name > sometextfile.txt on a Vostro 430 (dell computer model) a text file that looks like this:

Name
Vostro 430

So the code above "should" ignore the first line and compare "Vostro 430" in the if statements and then jump to one of the lables. It seems that I have some error though if I echo the out the batch script I can see that it is evaluating %A as a blank:

== "Vostro 430" goto vostro430
== "Optiplex 380" goto optiplex380

Any ideas where I messed up? I suspect some sort of string or syntax issue but I haven't been able to pin it down.

Upvotes: 0

Views: 5658

Answers (3)

jeb
jeb

Reputation: 82337

As aphoria pointed you need quotes around the %%A.

But the main problem is the output of the wmic command, as it outputs in unicode format.

Try this code to see the effect

FOR /F "tokens=* skip=1 delims=" %%A in ('wmic csproduct get name') do ( 
    echo .............1%%A2
)

The output will be something like

2............1TravelMate 7720
2............1

What happens here? The lines are appended with a <CR> character, so the 2 will be print at position 1 of the line.

You can avoid this with simply removing the last character from %%A

setlocal EnableDelayedExpansion
FOR /F "tokens=* skip=1 delims=" %%A in ('wmic csproduct get name') do ( 
    set "line=%%A"
    set "line=!line:~0,-1!"
    echo "!line!"
)

Or you use the TYPE command to normalize the output

wmic csproduct get name > wmicOutput.tmp
FOR /F "tokens=* skip=1 delims=" %%A in ('type wmicOutput.tmp') do ( 
    echo Works too "%%A"
    if "%%A"== "Vostro 430" goto :Vostro
)

Upvotes: 1

Aacini
Aacini

Reputation: 67216

The standard way to get a whole line in for /F command is via tokens=* or delims=", but not both. Use only delims this way:

FOR /F "skip=1 delims=" %%A in ('wmic csproduct get name') do ( ...

Also, you must add quotes in %%A value for the correct comparison in the if command, as aphoria said.

Upvotes: 1

aphoria
aphoria

Reputation: 20199

Try adding quotes around %%A...like this:

if "%%A" == "Vostro 430" goto vostro430
if "%%A" == "Optiplex 380" goto optiplex380

Upvotes: 1

Related Questions