More on Setting Environment variables

We had an internal thread about Setting Environment variables and someone posted a cool V1\V1.1 solution.

One workaround is to use System.Management (WMI). This should work on all versions of .NET Framework with WMI installed on the OS. You would retrieve the instance of the WMI Win32_Environment class, change the value, and commit. E.g.

To change a local system environment variable:

string envPath = "Win32_Environment.Name='SystemVariableNameHere'" + ",UserName='<SYSTEM>'";

ManagementObject envObject = new ManagementObject(envPath);

envObject["VariableValue"] = "NewSystemVariableValueHere";

envObject.Put(); // Save the change to the system

To change a local user environment variable:

string domainAlias = "DomainNameHere\\AliasHere";

string envPath = "Win32_Environment.Name='UserVariableNameHere'" + ",UserName='" + domainAlias + "'";

ManagementObject envObject = new ManagementObject(envPath);

envObject["VariableValue"] = "NewUserVariableValueHere";

envObject.Put();

To change an environment variable on a remote box, you would supply a ManagementScope object with connection configurations to the ManagementObject constructor.

You just have to love WMI....