Reputation: 6400
I am having a lot of trouble comparing a string in a variable to an actual string in batch. Here's the script:
set failure=0
for /F "usebackq delims=" %%L in (`"wmic PRINTER where name='10.146.2.52 - HP Color LaserJet CP5225n' GET Name 2>&1"`) do (
::Quotes around variable seem to have no effect. Same result w/ or w/o them.
if /I "%%L"=="No Instance(s) Available." set failure=1
echo %failure% %%L
)
Here's the output:
Why does the if statement fail? The values clearly match. Please help!!
Upvotes: 2
Views: 496
Reputation: 20189
I think the issue is the parentheses in the string No Instance(s) Available.
.
The easiest resolution is to probably just substring out the first part of the string, thereby ignoring the parentheses.
@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
SET failure=0
FOR /F "usebackq delims=" %%L in (`"wmic PRINTER where name='10.146.2.52 - HP Color LaserJet CP5225n' GET Name 2>&1"`) DO (
SET str=%%L
SET substr=!str:~0,11!
IF /I "!substr!"=="No Instance" SET failure=1
ECHO !failure! !substr!
)
Upvotes: 0
Reputation: 41234
The string often has more text before/after it - even if there is a cr there to deal with - and Wmic is an odd beast to handle.
You could do a separate test and pipe the result through find
or findstr
to set an errorlevel. Something like the following - or use the errorlevel that find
sets to 0 when the text is found.
wmic PRINTER where name='10.146.2.52 - HP Color LaserJet CP5225n' GET Name 2>&1 |find "No Instance" >nul && echo printer not detected
Enclose the %%L in quotes when you echo it to see if obvious trailing text is there.
This is what I get in debug, with the extra CR/0D and plus it gives you some nulls for good measure. :)
0B48:0100 4E 6F 20 49 6E 73 74 61-6E 63 65 28 73 29 20 41 No Instance(s) A
0B48:0110 76 61 69 6C 61 62 6C 65-2E 0D 0D 0A 0D 00 0A 00 vailable........
Upvotes: 1
Reputation: 82297
There are three different gotchas here.
1) Wmic appends sometimes an extra CR
character at the end of a line, which would be part of the string.
2) You can't access failure
with a percent expansion inside of a block.
3) The missing quotes around %%L
Try this
setlocal EnableDelayedExpansion
set failure=0
for /F "usebackq delims=" %%L in (`"wmic PRINTER where name='10.146.2.52 - HP Color LaserJet CP5225n' GET Name 2>&1"`) do (
set "line=%%L"
set "head=!line:~0,9!"
if "!head!"=="No Instan" set failure=1
echo 123-%%L-456
)
echo %failure%
Upvotes: 2