2

Question: What is simple, reliable way to add a folder to the system path in a batch script only once no matter how many times I run the script?

I need to add a folder to the path permanently. But I only want to add it one time, even if I run the script many times.

Attempts: I am comfortable adding the folder to the path in the environment and the registry:

SETX /m PATH "%PATH%;%MyFolder%"
SET PATH=PATH;%MyFolder%

Yet I need to guarantee it will not keep adding the same folder to the path variable every time it runs. My first thought is to compare strings to check if it already contains the folder, but I need help with the syntax:

REM If the PATH folder does not contain the folder already
IF NOT %MyFolder%==%PATH% (
  REM Add the folder to the path
)

Or is there a better way?

AndrewRalon
  • 496
  • 1
  • 9
  • 24
  • 1
    This is almost a duplicate of [How to check if directory exists in %PATH%?](http://stackoverflow.com/q/141344/1012053). See [my answer](http://stackoverflow.com/a/8046515/1012053) for a robust method to detect an existing path. – dbenham Oct 17 '14 at 00:34
  • @dbenham Your answer is a big help. I'm using `inPath` to do the heavy lifting now and it works great. I'm not sure what to do about answering this question, though... – AndrewRalon Oct 21 '14 at 14:44

1 Answers1

0

Here is a simple routine that only checks if the exact path is already listed and if it is not found, adds it to the PATH.

@echo off
call :AppendMachinePATH "%MyFolder%"
exit /b 0

:AppendMachinePATH <Path to Add>
for %%A in ("%PATH:;=" "%") do if /i "%%~A"=="%~1" exit /b 1
setx /m PATH "%PATH%;%MyFolder%"
set "PATH=%PATH%;%MyFolder%"
exit /b 0

(Written from memory, not tested)

David Ruhmann
  • 11,064
  • 4
  • 37
  • 47