I have a folder that I want to add to the PATH variable under Environment Variables (for the machine). I am appending the folder to the path via the registry setting. SYSTEM\CurrentControlSet\Control\Session Manager\Environment.
Here is a snippet of the code where I read the registry setting. And I perform a registry update on the setting, so nothing revolutionary.
String keyName = @"SYSTEM\CurrentControlSet\Control\Session Manager\Environment\";
string existingPathFolderVariable = (string)Registry.LocalMachine.OpenSubKey(keyName).GetValue("PATH", "", RegistryValueOptions.DoNotExpandEnvironmentNames);
string keyValue = @"c:\MyPath\";
if ( !existingPathFolderVariable.Contains(keyValue) )
{
if (!existingPathFolderVariable.EndsWith(";", StringComparison.InvariantCulture))
{
existingPathFolderVariable += ';';
}
Followed by code to update registry value, standard registry functions.
}
I tried various options of updating the registry including using powershell.
$oldpath = (Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH).path
$newpath = "$oldpath;c:\install\sysinternals"
Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH -Value $newPath
(Get-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH).Path
Though the path is updated and the values look correct, the path is no longer valid. The commands under the System32 folder are no longer valid. If I perform a ping, I get the unknown command message. Same for ipconfig and other commands.
I read that I could use the SetEnvironmentVariable function. But I do not want the values expanded. If I copy the line, delete the line, and add the line via the registry setting or UI, the problem is resolved.
Any suggestions on how to resolve the problem?