Skip to content

Instantly share code, notes, and snippets.

Embed
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;
$WM_SETTINGCHANGE = 0x1a;
$result = [UIntPtr]::Zero
[void] ([Win32.Nativemethods]::SendMessageTimeout($HWND_BROADCAST, $WM_SETTINGCHANGE, [UIntPtr]::Zero, "Environment", 2, 5000, [ref] $result))
}
@newradius

This comment has been minimized.

Copy link

@newradius newradius commented Jul 4, 2019

Nice one.

@DanGough

This comment has been minimized.

Copy link

@DanGough 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!

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