Monday, December 30, 2019

windows 8 - Append to System PATH variable without including the User's PATH variable


Imagine the following environment variables:


System PATH = C:\Windows
Bob's User PATH = C:\Users\Bob


In a command prompt the PATH command returns C:\Windows;C:\Users\Bob


After running setx /m PATH "C:\Node;%PATH%"
System PATH = C:\Node;C:\Windows;C:\Users\Bob


In a new command prompt the PATH command returns C:\Node;C:\Windows;C:\Users\Bob;C:\Users\Bob


Another user, Alice, logs in.
Alice's User PATH = C:\Users\Alice


On a command prompt the PATH command returns C:\Node;C:\Windows;C:\Users\Bob;C:\Users\Alice


Bob has a duplicate path in his PATH variable, and Alice has Bob's paths in her PATH variable.


Is there a way to append to the System PATH without polluting it with the current user's PATH?


Answer



In Windows 7, you can look up the System Path with


reg query "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /v path

If that still works on Windows 8, then use that to build the new value.


You'll have to figure out how to parse the output of reg query
Here's something that might work:


for /f "tokens=1,2*" %a in ('reg query "HKLM\…\Environment" /v path') do set currentValue=%c

where



  • the 'reg query "HKLM\…\Environment" /v path' string
    is the reg query command (given above) enclosed in single quotes.

  • a, currentValue, and c are variable names. 
    You can choose whatever variable names you want,
    with the constraints that the a and the c must be single letters, two letters apart
    (e.g., you could use n and p, or x and z).

  •                             for /f "options" %variable in ('command1') do command2
    runs command1, parses the output, assigns value(s) to the %variable(s) (%a, above; but see also below) and executes command2.

  • tokens=1,2* means that %a gets the first token (word) of each (remaining) line,
    %b gets the second word, and %c gets the rest of the line.



    • The first word is path (the value name).

    • The second word is REG_EXPAND_SZ (the value type).

    • The rest of the line is the value.


    (You could just use tokens=2* and then currentValue=%b.)



So, after executing the above, you should be able to do


setx PATH "C:\Node;%currentValue%" /m


  • If you do this in a script (a .BAT file), use %%a and %%c.

  • Be sure to test this with echo commands before you do it with setx.


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...