简体   繁体   中英

How I can update the extensionAttribute3 Attribute in Active Directory with Powershell class in c#?

hi i want update the active directory with powershell and asp.net for this i use this code:

costCenter = "777";

public string SetADUser(string Auth_Password,string sAMAccountName, string CostCenter)
        {

            Security key = new Security();

            try
            {
                SecureString pw = new SecureString();

                foreach (char x in Auth_Password)
                {
                    pw.AppendChar(x);
                }

                InitialSessionState initial = InitialSessionState.CreateDefault();
                Environment.SetEnvironmentVariable("ADPS_LoadDefaultDrive", "0");
                initial.ImportPSModule(new string[] { "ActiveDirectory" });

                PSCredential crend = new PSCredential(ADNAME, pw);

                using (Runspace runspace = RunspaceFactory.CreateRunspace(initial))
                {
                    runspace.Open();
                    using (Pipeline p = runspace.CreatePipeline())
                    {
                        Command command = new Command("Set-ADUser");
                        command.Parameters.Add("Identity", sAMAccountName);
                        command.Parameters.Add("Replace","@{extensionAttribute3=" + "'" + CostCenter + "'" + "}"); ?? what is here wrong
                        //command.Parameters.Add("extensionAttribute3", CostCenter);
                        command.Parameters.Add("Credential", crend);

                        p.Commands.Add(command);

                        p.Invoke();

                        return string.Empty;

                    }
                }
            }
            catch (Exception ex)
            {

                return ex.Message;
            }
            finally
            {

            }
        }

this is the error:

The Parameter "Replace" can not bind. The Value "@{extensionAttribute3='777'}" from typ "System.String" can not convert to "System.Collections.Hashtable".

How I can do this?

@{} is a powershell-shortcut to create a hashtable. In C# you should create a hashtable in the normal C#-way.

var ht = new Hashtable { { "extensionAttribute3", CostCenter } };
command.Parameters.Add("Replace", ht);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM