Windows – using powershell to update system path doesn’t immediately work

pathpowershellwindows

I am trying to use powershell to update Windows system path by :

$oldpath = (Get-ItemProperty -Path ‘Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment’ -Name PATH).path
$newpath = "$oldpath;C:\nuget"
Write-Output "PATH:$newpath"
Set-ItemProperty -Path 'Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment' -Name PATH -Value $newPath -Force
Get-ItemProperty -Path ‘Registry::HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\Session Manager\Environment’ -Name PATH   

it seems work, Get-ItemProperty does show "C:\nuget" is added into path. The problem is then i start a new powershell console or a command line console, and type "nuget", I still get "The term 'nuget' is not recognized as the name of a cmdlet, function, script file, or operable program"

in the new powershell console, if I rerun Get-ItemProperty, it shows the new Path is there, it's just doesn't immediately take effect in current user session. If I run "set " in cmd console, the new Path wasn't there in PATH variable.

BTW, after Set-ItemProperty was run, I checked control pannel->System->Advanced system setting->Environment Variables, the new Path I added is there.

I found if I manually modify the Path through Windows system setting, it will take effect immediately ( new cmd/powershell will have it); but if the path is modified by powershell Set-ItemProperty command, then I have to logoff, then login, then new Path will take effect.

Feels like the system Path is cached in the current user login session.

Best Answer

When you change the PATH variable by using the control panel, when you click "OK", the control panel sends a WM_SETTINGCHANGE message to all the opened windows, so they know that the environments variables has been changed.

So, if you don't want to logoff, you must send WM_SETTINGCHANGE yourself by creating/finding a little program that sends this message according to the documentation: https://msdn.microsoft.com/en-us/library/windows/desktop/ms725497%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396