How to set Windows environment variables in Rust without restarting command prompt?

76 Views Asked by At

I need to programmatically set some system wide Windows environment variables using a tool written in Rust. My approach is to update the relevant registry entries and then broadcast a WM_SETTINGCHANGE message:

let hklm = RegKey::predef(HKEY_LOCAL_MACHINE);
let (environment, _) = hklm.create_subkey("System\\CurrentControlSet\\Control\\Session Manager\\Environment")?;
environment.set_value("MY_ENV_VAR", "SOME_VALUE")?;

// WM_SETTINGCHANGE
let message = w!("System\\CurrentControlSet\\Control\\Session Manager\\Environment");
let mut result = 0;
let success = unsafe {
    SendMessageTimeoutW(
        HWND_BROADCAST,
        WM_SETTINGCHANGE,
        0,
        message as _,
        0,
        1000,
        &mut result,
    )
};
if success == 0 {
    eprintln!("Failed to send setting changed message.");
}

However, when the tool finishes executing and I run set, I do not see my environment variables being set. What is the correct way to set environment variables so that they are visible in the currently running command prompt process?

Edit:

I should add that this tool also needs to run in a Windows Server Core Docker image, so any solution needs to support permanently setting the environment variables there.

0

There are 0 best solutions below