Skip to content

Instantly share code, notes, and snippets.

@alphp
Created August 27, 2018 04:08
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save alphp/78fffb6d69e5bb863c76bbfc767effda to your computer and use it in GitHub Desktop.
Save alphp/78fffb6d69e5bb863c76bbfc767effda to your computer and use it in GitHub Desktop.
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
Copy link

Nice one.

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

@AdamDanischewski
Copy link

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