Skip to content

Instantly share code, notes, and snippets.

@segevfiner
Created November 24, 2021 13:56
Show Gist options
  • Save segevfiner/584599f9737c5c28cfdd53a4f30acbac to your computer and use it in GitHub Desktop.
Save segevfiner/584599f9737c5c28cfdd53a4f30acbac to your computer and use it in GitHub Desktop.
Refresh the Windows environment variables from the registry
<#
.SYNOPSIS
Refresh the Windows environment variables from the registry.
.DESCRIPTION
Refresh the Windows environment variables from the registry.
.INPUTS
None.
.OUTPUTS
None.
#>
using namespace RefreshEnvironment
$source = @"
using System;
using System.Runtime.InteropServices;
namespace RefreshEnvironment
{
public class RefreshEnvironment
{
public static readonly IntPtr HWND_BROADCAST = (IntPtr)0xffff;
public const uint WM_WININICHANGE = 0x001A;
public const uint WM_SETTINGCHANGE = WM_WININICHANGE;
[Flags]
public enum SendMessageTimeoutFlags : uint
{
SMTO_NORMAL = 0x0,
SMTO_BLOCK = 0x1,
SMTO_ABORTIFHUNG = 0x2,
SMTO_NOTIMEOUTIFNOTHUNG = 0x8,
SMTO_ERRORONEXIT = 0x20
}
[DllImport("user32.dll", CharSet=CharSet.Auto, SetLastError=true)]
public static extern IntPtr SendMessageTimeout(
IntPtr hWnd,
uint Msg,
UIntPtr wParam,
string lParam,
SendMessageTimeoutFlags fuFlags,
uint uTimeout,
out UIntPtr lpdwResult
);
}
}
"@
Add-Type -TypeDefinition $source
$result = [UIntPtr]::Zero
if (![RefreshEnvironment]::SendMessageTimeout(
[RefreshEnvironment]::HWND_BROADCAST,
[RefreshEnvironment]::WM_SETTINGCHANGE,
[UIntPtr]::Zero,
"Environment",
[RefreshEnvironment+SendMessageTimeoutFlags]::SMTO_ABORTIFHUNG,
5000,
[ref]$result
)) {
throw [ComponentModel.Win32Exception]::new([Marshal]::GetLastWin32Error())
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment