Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 412
  • Last Modified:

Batch (CMD) file issue within expanded IF construct

Hi,

I have the following method of checking a file version working:
filever.exe /B /A /D "C:\Program Files\Folder\File.exe" | find "1.1.1.1" >nul
If '%errorlevel%'=='0' Goto DoSomething

Open in new window

But it doesn't work if I do it inside an expanded IF block like this:
if exist "C:\Program Files\Folder\File.exe" (
   filever.exe /B /A /D "C:\Program Files\Folder\File.exe" | find "1.1.1.1" >nul
   if '%errorlevel%'=='0' (
      rem Something here
   ) else (
      rem Something here
   )
) else (
   rem Something here
)

Open in new window

It no longer does the version match correctly.  The %errorlevel% is always 0.  
I tried redirecting the output of the filever.exe (without the pipe) to a text file and it was as expected.
I then tried redirecting the output of the find.exe to a text file and there was no output.

It's as though the piping to the FIND command no longer works inside the IF construct.  Any idea why?  Thanks!
0
cantoris
Asked:
cantoris
1 Solution
 
oBdACommented:
You need to enable "delayed expansion" for that (enter "help set" in a command prompt for details) and then use "!" to expand the variables inside the loop:
setlocal enabledelayedexpansion
if exist "C:\Program Files\Folder\File.exe" (
   filever.exe /B /A /D "C:\Program Files\Folder\File.exe" | find "1.1.1.1" >nul
   if '!errorlevel!'=='0' (
      rem Something here
   ) else (
      rem Something here
   )
) else (
   rem Something here
)

Open in new window

0
 
cantorisAuthor Commented:
Perfect, thanks.  Not seen that feature before!
0

Featured Post

[Webinar] Cloud and Mobile-First Strategy

Maybe you’ve fully adopted the cloud since the beginning. Or maybe you started with on-prem resources but are pursuing a “cloud and mobile first” strategy. Getting to that end state has its challenges. Discover how to build out a 100% cloud and mobile IT strategy in this webinar.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now