Skip navigation

JSI Tip 4263. How do I add a folder to the Windows 2000 / Windows XP PATH, in a batch?


I have scripted SetPath.bat which accomplishes the following tasks:

1. Adds the specified folder to your path, if it is not already present.

2. Creates the folder, if it is missing.

NOTE: The new PATH will NOT be active until the computer is restarted. 

NOTE: You can use workstation.bat to run SetPath.bat on all the workstations in your domain.

Usage:

SetPath NewFolder

where NewFolder is the fully qualified new folder path.

Examples:

SetPath "C:\Program Files\My Stuff"

SetPath D:\utility

NOTE: If the NewFolder string already exists, it will not be added. If D:\utilityManager already exists in the PATH, then D:\utility will NOT be appended.

NOTE: The NewFolder tree can NOT be more than 8 branches deep.

SetPath.bat uses Reg.exe from the Windows 2000 Support Tools.

SetPath.bat contains:

@Echo Off
SetLocal
if \{%1\} EQU \{\} goto syntax
set folder=%1
set folder=%folder:"=%#
set folder=%folder:/#=%
set folder=%folder:#=%
set drive=%folder:~0,2%
set string=%folder:~3,256%
%drive%
for /f "Tokens=1-8 Delims=\" %%i in ('@echo %string%') do call :parse "%%i" "%%j" "%%k" "%%l" "%%m" "%%n" "%%o" "%%p"
goto continue
:syntax
@echo Syntax: SetPath NewFolderPath
goto :end
:parse
if %1 EQU "" goto :EOF
if exist %1 goto next
md %1
:next
cd %1
shift
goto parse
:continue
Set KEY="HKLM\System\CurrentControlSet\Control\Session Manager\Environment"
Set prevpath=
Set newpath=
For /F "tokens=2,*" %%i in ('reg.exe Query %KEY% /v Path ^|findstr.exe /r /i /C:"Path.*REG"') Do @Set prevpath=%%j
If Not Defined prevpath @Echo Failed to find the path using reg.exe. & goto :end
Set newpath=%prevpath%;%folder%
Set newpath=%newpath:;;=;%
Echo %prevpath%|findstr.exe /i /C:"%folder%" >NUL
If %ErrorLevel% NEQ 0 reg.exe ADD %KEY% /v PATH /t REG_EXPAND_SZ /d "%newpath%" /f
:end
EndLocal


Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish