如何在c#中使用Powershell类更新活动目录中的extensionAttribute3属性

本文关键字:活动 属性 extensionAttribute3 更新 Powershell | 更新日期: 2023-09-27 17:50:13

嗨,我想用powershell和asp.net更新活动目录,为此我使用以下代码:

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
            {
            }
        }

这是错误:

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

我该怎么做?

如何在c#中使用Powershell类更新活动目录中的extensionAttribute3属性

@{}是powershell创建散列表的快捷方式。在c#中,你应该用普通的c#方式创建一个哈希表。

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