Reference default path in powershell script

Viewed 85

Is there a way to call the system path if the path has been changed in the current terminal? i.e.:

$env:Path = "C:\some new path"   
#some coding that requires a different path set up
$env:Path = $defaultPath #would have to define $defaultPath by calling the system default path
2 Answers

Use the following to reload the $env:PATH environment variable from the registry, as future sessions would see it (assuming no further relevant registry updates are made).

If your current session hasn't made any relevant registry updates, this is the same as getting the value that was in effect on session startup - barring any dynamic additions via a $PROFILE script:

$env:PATH = [Environment]::GetEnvironmentVariable('Path', 'Machine'),
            [Environment]::GetEnvironmentVariable('Path', 'User') -join ';'

Note:

  • A process' effective $env:PATH value is a composite value of a machine-level and a user-level registry entry, with the machine-level definition taking precedence, as reflected in the two .NET API calls above.

    • Note that the underlying registry locations - HKEY_LOCAL_MACHIN\System\CurrentControlSet\Control\Session Manager\Environment and HKEY_CURRENT_USER\Environment - are REG_EXPAND_SZ registry values, i.e. they may be defined in terms of other environment variables, such as %SystemRoot% and %ProgramFiles%.

    • Both the .NET API calls above - using [Environment]::GetEnvironmentVariable() - and PowerShell's Get-ItemProperty and Get-ItemPropertyValue cmdlets expand (interpolate) such references and return verbatim paths - which is what new processes see by default too.

  • Given the above, the only way to robustly retrieve the value that was in effect at session startup time is to save it in a variable at startup time.

It's still stored in the registry so you can just query it:

  • Located: HKLM:\System\CurrentControlSet\Control\Session Manager\Environment
$key = "HKCU:\Environment",
       "HKLM:\System\CurrentControlSet\Control\Session Manager\Environment"
       
(Get-ItemPropertyValue -Path $key -Name Path) -Join ';'

Querying the key using Get-ItemPropertyValue (as suggested by Mklement) will give you just the property's value.

Related