How do refresh environment variable changes from a different user session

environment-variableswindows-server-2008

I came from Here. My question is specifically about getting environment variables updates from a different session. If I update the system environment variable in one user session, I found the other sessions must log out/in to apply the change. But if I just run SET in other sessions, I can see the change. But any new process won't pick up the change.

Is this behavior by design? Is there a way for other users to get the new environment variable without logging off?

Best Answer

There is a system-level API call "SendMessageTimeout " that can be PInvoked using PowerShell:

Invoke-WMSettingsChange
http://poshcode.org/2049

Description: Notifies other processes that the global environment block has changed. This lets other processes pick changes to ENV: without having to reboot or logoff/logon. A non-zero result from SendMessageTimeout indicates success.

if (-not ("win32.nativemethods" -as [type])) {
    # import sendmessagetimeout from win32
    add-type -Namespace Win32 -Name NativeMethods -MemberDefinition @"  

[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern IntPtr SendMessageTimeout(
   IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam,
   uint fuFlags, uint uTimeout, out UIntPtr lpdwResult);
"@
}

$HWND_BROADCAST = [intptr]0xffff;
$WM_SETTINGCHANGE = 0x1a;
$result = [uintptr]::zero

# notify all windows of environment block change
[win32.nativemethods]::SendMessageTimeout($HWND_BROADCAST, $WM_SETTINGCHANGE,
        [uintptr]::Zero, "Environment", 2, 5000, [ref]$result);

More information:

https://stackoverflow.com/questions/22734043/activate-registry-changes-after-setting-new-path-environment-variable