Page 1 of 1

If else logic question [SOLVED]

Posted: 19 Aug 2021 09:17
by atfon
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.

Re: If else logic question

Posted: 19 Aug 2021 09:40
by ShadowThief
You're setting and using nPad and nPadLocin the same code block, so you need to use delayed expansion to reference the variable.

Re: If else logic question

Posted: 19 Aug 2021 09:51
by atfon
Hi Shadowthief. Yes. I do have setlocal enabledelayedexpansion in my code.

Re: If else logic question

Posted: 19 Aug 2021 10:26
by ShadowThief
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%

Re: If else logic question [SOLVED]

Posted: 19 Aug 2021 10:40
by atfon
Aha! I get it now. Thanks again, Shadowthief. The learning continues. :)