Update Environment variable on remote machine using Management Object in C#

Following is the code to update environment variable in remote machine. By using this method we are not able to add new environment variable but we can update existing environment variable.


/// <param name="MachineName">Remote machine which environment variable need to update.</param>
/// <param name="username">username of remot machine which is use for login </param>
/// <param name="password">password of remote machine which is use for login</param>
/// <param name="VariableName">Varaible name which need to be update</param>
/// <param name="VariableValue">new value of varialbe</param>
public void UpdateEnvironmentVariable(string MachineName, string username, string password, string VariableName, string VariableValue)
{
    string ResultInfo = "";
    bool IsFound = false;
    ManagementObjectSearcher query = null;
    ManagementObjectCollection queryCollection = null;

    ConnectionOptions opt = new ConnectionOptions();

    opt.Impersonation = ImpersonationLevel.Impersonate;
    if (!chkLocal.Checked)
    {
        opt.EnablePrivileges = true;
        opt.Username = username;
        opt.Password = password;
        opt.Impersonation = ImpersonationLevel.Impersonate;
        opt.EnablePrivileges = true;
    }
    try
    {
        ManagementPath p = new ManagementPath("\\\\" + MachineName + "\\root\\cimv2");

        ManagementScope msc = new ManagementScope(p, opt);

        SelectQuery q = new SelectQuery("Win32_Environment");

        query = new ManagementObjectSearcher(msc, q, null);
        queryCollection = query.Get();

    

        ResultInfo += "\r\nTotal Count - " + queryCollection.Count;
        foreach (ManagementObject envVar in queryCollection)
        {
            if (envVar["Name"].ToString() == VariableName.Trim())
            {
                ResultInfo += "\r\n" + "System environment variable " + envVar["Name"] + " = " + envVar["VariableValue"];
                string OldValue = envVar["VariableValue"].ToString();
                envVar.SetPropertyValue("VariableValue", VariableValue.Trim());
                envVar.Put();
                IsFound = true;
                ResultInfo += "\r\n" + "Message:\tEnvironment variable update successfully";
                ResultInfo += "\r\n" + "OldValue: " + OldValue;
                ResultInfo += "\r\n" + "NewValue: " + VariableValue.Trim();
                break;
            }
        }
        if (IsFound == false)
            ResultInfo += "\r\nNot Found:\t" + txtVariableName.Text.Trim() + " not found in environment vairable";
    }
    catch (ManagementException Ex)
    {
        ResultInfo += "\r\nError:\t" + Ex.Message;
        ResultInfo += "\r\nStack:\t" + Ex.StackTrace;
    }
    catch (System.UnauthorizedAccessException Ex)
    {
        ResultInfo += "\r\nError:\t" + Ex.Message;
        ResultInfo += "\r\nStack:\t" + Ex.StackTrace;
    }
    catch (Exception Ex)
    {
        ResultInfo += "\r\nError:\t" + Ex.Message;
        ResultInfo += "\r\nStack:\t" + Ex.StackTrace;
    }
}

Folloiwng are some points to run above code successfully –
1. “Remote Procedure Call (RPC) Locator” and “Remote Procedure Call (RPC)” service should be start on remote machine.
– To start above services, type services.msc on run prompt and search for above services. Right click on each service and set it to automatic and start it.

2. Window Firewall should be configure or should be off on remote machine.

3. A user (which will access registry of remote machine) must be added with administrator privileges on remote machine. To add user with administrator privileges do following thing
– Right click on MyComputer and click on manage.
– Expand Local users and groups
– Double click on groups and then double click on administrator group.
– Add user (which will access registry of remote machine from another machine) in this group.

Advertisements
Posted in Uncategorized. Leave a Comment »

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: