3

A script needs to add a program to the Windows PATH. Another script needs to remove that same program from the Windows PATH. For compatibility issues, the script needs to work on most if not all flavors of Windows.

Which registry key (or keys) consistently store the PATH on a wide range of Windows machine types?

For example, on my Windows 10 Home Edition laptop, the PATH is stored in the Path property of the following key:

HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment

But another user informs me this key is not available on his or her Windows machine.

So what is the complete list of key location possibilities?

Note that the scripts are targeting the keys directly because the changes to the PATH must persist after the end of runtime. Other approaches seem to only temporarily change the PATH while the program is running.

CodeMed
  • 9,527
  • 70
  • 212
  • 364
  • 2
    `HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment` for Win XP till Server 2012 R2, Win10 Enterprise, Win10 Pro – Kundan Jan 08 '20 at 17:34
  • this might be helpful https://learn.microsoft.com/en-us/dotnet/api/system.environmentvariabletarget?redirectedfrom=MSDN&view=netframework-4.8 – Kundan Jan 08 '20 at 17:35

1 Answers1

4

From PowerShell, persistently set the PATH environment by using the following method:

[Environment]::SetEnvironmentVariable( 'VARIABLE_NAME', 'VALUE', [EnvironmentVariableTarget]::Machine )

To remove the environment variable, set the environment variable value to $null:

[Environment]::SetEnvironmentVariable( 'VARIABLE_NAME', $null, [EnvironmentVariableTarget]::Machine )

As for why your users are missing that registry key? That sounds like a larger problem because HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment is where the System Environment Variables are stored and retrieved from. It's been that way since XP, and the documentation states this as far back as .NET Framework 2.0.

If that key is missing on someone's machine, I'd wager the user is either not looking in the right place, or some sort of malware could be the cause.


If you want to set the environment variable at the process level, as asked in the comments, you can use the $env: variable to read and set environment variables at the process level:

$env:VARIABLE_NAME = 'VALUE'
codewario
  • 19,553
  • 20
  • 90
  • 159
  • Can you show how to set the PATH variable temporarily also, so that it also is available immediately in the same session in addition to having it be available permanently? – CodeMed Jan 08 '20 at 18:57
  • That one's easy, `$env:VARIABLE_NAME = 'VALUE'`. This will set the environment variable at the process level, so the current process and child processes will be able to see the variable. – codewario Jan 08 '20 at 19:27