Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I handle Windows PATH variable expansion when set from PowerShell?

I am tweaking the PATH on several W2k3 servers in PowerShell to convert certain paths with blank spaces to their 8.3 equivalents. After several regex transformations, I run the following two commands:

# Set the path for this process
$env:PATH = $path
# Set the path for the Machine
[System.Environment]::SetEnvironmentVariable('PATH', $path,[System.EnvironmentVariableTarget]::Machine) 

After running them, the path is changed in ways I didn't intend. %SystemRoot% is uniformly expanded to C:\Windows. I can't see where this signals the apocalypse, but I'd rather keep the %SystemRoot%, so I fiddled until I got %SystemRoot% to appear in the path again, but when I do the path no longer expands and no longer works. Echoing the path at the CLI returns an unexpanded string (this is wrong) and commands in the SystemRoot can no longer be found.

If I then add a null entry to the Path ";;", without altering any other text in the PATH, it begins to work correctly.

So my question is how to alter the path programmatically using PowerShell so as not to muck up variable expansion within the path?

like image 407
codepoke Avatar asked Jan 23 '12 16:01

codepoke


1 Answers

As far as I can tell, you can't do this with the [Environment]::SetEnvironmentVariable() method and you can't do this with the Registry provider. However you can access the system Path env var in the registry using the Microsoft.Win32.RegistryKey class like so:

C:\PS> $key = [Microsoft.Win32.Registry]::LocalMachine.OpenSubKey('SYSTEM\CurrentControlSet\Control\Session Manager\Environment', $true)
C:\PS> $path = $key.GetValue('Path',$null,'DoNotExpandEnvironmentNames')
C:\PS> $path
...;%systemroot%\System32\WindowsPowerShell\v1.0\
C:\PS> $key.SetValue('Path', $path + ';%Windir%\Symbols', 'ExpandString')
C:\PS> $key.Dispose()

This will allow you to save the updated PATH and preserve the variables that appear in the Path value.

like image 159
Keith Hill Avatar answered Sep 28 '22 08:09

Keith Hill