How to get the value of the PATH environment variable without expanding tokens? How to get the value of the PATH environment variable without expanding tokens? powershell powershell

How to get the value of the PATH environment variable without expanding tokens?


This isn't PowerShell per se, but a "feature" of the underlying Windows registry. The Path variable is of type REG_EXPAND_SZ which automatically expands environment variables on retrieval. I don't think you can get around it with the built-in cmdlets, but you can with the .NET Microsoft.Win32.Registry APIs. Use the RegistryKey.GetValue overload with RegistryValueOptions.DoNotExpandEnvironmentNames:

$regKey = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey('SYSTEM\CurrentControlSet\Control\Session Manager\Environment', $true)$regKey.GetValue('Path', $null, "DoNotExpandEnvironmentNames")

when it is time to save the variable, use the overload of SetValue with RegistryValueKind.ExpandString to save it with the correct type:

$regKey.SetValue("Path", $new_path, "ExpandString")


Without using the .NET [Microsoft.Win32.Registry] type: one-liners for user and system Path entries.

(Get-Item -path "HKCU:\Environment" ).GetValue('Path', '', 'DoNotExpandEnvironmentNames')(Get-Item -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" ).  GetValue('Path', '', 'DoNotExpandEnvironmentNames')