# Add C# code for sending the system-wide environment change notification
Add-Type @"
using System;
using System.Runtime.InteropServices;
public class NotifyUser {
[DllImport("user32.dll", SetLastError = true, CharSet = CharSet.Auto)]
public static extern bool SendNotifyMessage(IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam);
public static void NotifyUserEnvironmentVariableChanged() {
const int HWND_BROADCAST = 0xFFFF;
const uint WM_SETTINGCHANGE = 0x001A;
SendNotifyMessage((IntPtr)HWND_BROADCAST, WM_SETTINGCHANGE, (UIntPtr)0, "Environment");
}
}
"@ -Language CSharp
# Function to set the environment variable for all users using .NET
function Set-EnvVarForAllUsers {
param(
[string]$VarName,
[string]$VarValue
)
# Set the environment variable for the system using .NET method (affects new processes)
[System.Environment]::SetEnvironmentVariable($VarName, $VarValue, [System.EnvironmentVariableTarget]::Machine)
# Verify the value has been set (for the system environment)
$envValue = [System.Environment]::GetEnvironmentVariable($VarName, [System.EnvironmentVariableTarget]::Machine)
Write-Host "$VarName has been set to: $envValue"
}
# Set the SECRET_KEY environment variable to "xyz" for all users (system-wide)
Set-EnvVarForAllUsers -VarName "SECRET_KEY" -VarValue "xyz"
# Call the function to notify the system about the environment change
[NotifyUser]::NotifyUserEnvironmentVariableChanged()
Haven’t tried the above, but above P/Invoke low level API on windows can make the env. vars show up for new processes outside of Windows Explorer without a restart of host.
The C# code was taken from an earlier post by me noted here: Node Manager UX and Issues - #239 by Shu.