If else logic question [SOLVED]

Discussion forum for all Windows batch related topics.

Moderator: DosItHelp

Post Reply
Message
Author
atfon
Posts: 178
Joined: 06 Oct 2017 07:33

If else logic question [SOLVED]

#1 Post by atfon » 19 Aug 2021 09:17

I'm having some issues with the logic of an if else block. I can get it to work just fine if I rely on goto statements, but I'd rather not. I am simply checking if an exe file exists and then capturing the version if it does else setting the variable to Not Installed otherwise. The code to capture the version works just fine:

Code: Select all

set "nPad=%windir%\notepad.exe"
set "nPadloc=%nPad:\=\\%
for /f "tokens=2 delims==" %%e in ('wmic datafile where "name='%nPadloc%'" get version /value') do for /f "delims=" %%f in ("%%e") do set "nPadv=Version: %%e"
echo %nPadv%
However, this does not work if I place it in an if else block:

Code: Select all

if exist "%windir%\notepad.exe" (
set "nPad=%windir%\notepad.exe"
set "nPadloc=%nPad:\=\\%
for /f "tokens=2 delims==" %%e in ('wmic datafile where "name='%nPadloc%'" get version /value') do for /f "delims=" %%f in ("%%e") do set "nPadv=Version: %%e"
) else (
set "nPadv=Not Installed"
)
echo %nPadv%
I'm using notepad.exe as an example, but this could be any file. I'm sure I'm missing something obvious, but I haven't been able to discover what it is. Any help would be appreciated.
Last edited by atfon on 19 Aug 2021 14:05, edited 1 time in total.

ShadowThief
Expert
Posts: 1160
Joined: 06 Sep 2013 21:28
Location: Virginia, United States

Re: If else logic question

#2 Post by ShadowThief » 19 Aug 2021 09:40

You're setting and using nPad and nPadLocin the same code block, so you need to use delayed expansion to reference the variable.

atfon
Posts: 178
Joined: 06 Oct 2017 07:33

Re: If else logic question

#3 Post by atfon » 19 Aug 2021 09:51

Hi Shadowthief. Yes. I do have setlocal enabledelayedexpansion in my code.

ShadowThief
Expert
Posts: 1160
Joined: 06 Sep 2013 21:28
Location: Virginia, United States

Re: If else logic question

#4 Post by ShadowThief » 19 Aug 2021 10:26

You may have it enabled, but you aren't using it. In order to do that, you need to use the !variable! syntax instead of the traditional %variable% syntax.

Code: Select all

if exist "%windir%\notepad.exe" (
set "nPad=%windir%\notepad.exe"
set "nPadloc=!nPad:\=\\!"
for /f "tokens=2 delims==" %%e in ('wmic datafile where "name='!nPadloc!'" get version /value') do for /f "delims=" %%f in ("%%e") do set "nPadv=Version: %%e"
) else (
set "nPadv=Not Installed"
)
echo %nPadv%

atfon
Posts: 178
Joined: 06 Oct 2017 07:33

Re: If else logic question [SOLVED]

#5 Post by atfon » 19 Aug 2021 10:40

Aha! I get it now. Thanks again, Shadowthief. The learning continues. :)

Post Reply