Append entries to Windows user PATH from script or command line

If you have to work in a Windows environment where you do not want to or cannot change the system level PATH, you can usually still use the “setx” command to change the user level PATH variable.

But what if you want to add (append) a directory to the user level PATH? The following would set your user PATH variable to the full (system + user) PATH plus the appended directory.

setx PATH "%PATH%;c:\whatever\else"

But this would duplicate the system PATH into your user PATH variable, which would ultimately cause duplicate entries in the full PATH.

Instead we want to append only to the user PATH variable. Unfortunately, to get its value from the Windows command-line you must query the “HKCU\Environment” registry entry and then parse the relevant part from the output string.

I wrote the add-to-user-path.bat script below to fix the problem. It has been tested on Windows 7, where “req query” uses 4 spaces to delimit its output, and it works even when the user PATH value already contains spaces:

@echo off 
setlocal EnableDelayedExpansion 

if %1.==. ( 
  echo Usage: %0 directory 
  goto End 
) 

for /f "skip=2 tokens=*" %%A in ('reg query "HKCU\Environment" /v PATH') do ( 
   set regstr=%%A
    
   for /f "tokens=3 delims=|" %%X in ("!regstr:    =^|!") do ( 
     setx PATH "%%X;%1" 
     echo PATH changes will only take effect for newly started processes. 
   ) 
) 

:End 

One thought on “Append entries to Windows user PATH from script or command line

  1. Thank you for posting this; it was just what I was trying to do.
    One thing thou; there is an extra space at the end of the line

    for /f “skip=2 tokens=*” %%A in (‘reg query “HKCU\Environment” /v PATH’) do (
    set regstr=%%A

    That messes up the registry entry, and its not recognized by the system.

    Thanks again

Leave a comment