1

I am seeing some strange behavior of a Windows batch script. When PATH is set outside an if block, its value is retained but the value is not retained when set inside the if block.

Here's a minimal .bat file that shows the problem.

@echo off

echo %*

set PATH=c:\Windows;
set "PATH=c:\Program Files\Siemens\NX 9.0\UGII;%PATH%"
PATH
set "PATH=c:\Program Files\Siemens\NX 9.0\UGII\managed;%PATH%"
PATH

set PATH=c:\Windows;

set arg=%1
if "%arg%" == "a" (
   echo "------------------------------------------"
   set "PATH=c:\Program Files\Siemens\NX 9.0\UGII;%PATH%"
   PATH
   set "PATH=c:\Program Files\Siemens\NX 9.0\UGII\managed;%PATH%"
   PATH
)

The output of the script when invoked with one a as the only argument.

a
PATH=c:\Program Files\Siemens\NX 9.0\UGII;c:\Windows;
PATH=c:\Program Files\Siemens\NX 9.0\UGII\managed;c:\Program Files\Siemens\NX 9.0\UGII;c:\Windows;
"------------------------------------------"
PATH=c:\Program Files\Siemens\NX 9.0\UGII;c:\Windows;
PATH=c:\Program Files\Siemens\NX 9.0\UGII\managed;c:\Windows;

As you can see, the directory "c:\Program Files\Siemens\NX 9.0\UGII" is missing from the last line of output.

Is this expected?

Is there a way to make this work without requiring PATH to be set only once inside the if block?

R Sahu
  • 204,454
  • 14
  • 159
  • 270
  • Aside from the link I posted, you do realize that this does not permanently change the `PATH` variable. You would need to use `SETX` for that. – Squashman Sep 13 '18 at 19:10
  • @Squashman, no I did not know that. – R Sahu Sep 13 '18 at 19:12
  • @Squashman, I need to change the PATH only in the script. `setx` is not the right command for my needs. Thanks for the info though. – R Sahu Sep 13 '18 at 19:53
  • Then I would advise that you be more careful with which directory paths you remove. Usually not a good idea to remove SYSTEM32. – Squashman Sep 14 '18 at 02:30
  • @Squashman, of course. The posted code was indended to be a [mcve]. – R Sahu Sep 14 '18 at 15:27

0 Answers0