Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
PowerShell module for send WM_SETTINGCHANGE after change Environment variables in Windows
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);
function Send-SettingChange {
$HWND_BROADCAST = [IntPtr] 0xffff;
$result = [UIntPtr]::Zero
[void] ([Win32.Nativemethods]::SendMessageTimeout($HWND_BROADCAST, $WM_SETTINGCHANGE, [UIntPtr]::Zero, "Environment", 2, 5000, [ref] $result))
Copy link

newradius commented Jul 4, 2019

Nice one.

Copy link

DanGough commented Dec 5, 2019

Thanks, just what I was looking for!

I'm using [System.Environment]::SetEnvironmentVariable under the System account (via psexec /s) to set a machine level variable and the user cannot see it until I run this code.

However, I either have to run the code as the user for it to work, or I have to run my process under the system account interactively (e.g. psexec /s /i).

Turns out when I run my original code interactively with /s /i, SetEnvironmentVariable works as intended now, and I no longer need this snippet!

Copy link

AdamDanischewski commented Mar 14, 2022

Works great! Thanks, it's a lot more comforting to use this then to kill explorer.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment