如何使用C#和Powershell类远程访问我的Active Directory服务器

时间:2012-10-24 10:41:27

标签: c# asp.net powershell active-directory remote-server

我必须构建一个Web应用程序,可以在ActiveDirectory中添加一个关于powerhell命令的新用户,我不知道如何做到这一点。

如果我为Exchangeserver执行此操作,则可以正常运行。

这里是我在Exchange Server中添加联系人的代码:

string URL = "http://server141.test-company.com/PowerShell/";
string Schema ="http://schemas.microsoft.com/powershell/Microsoft.Exchange";

public string CreateRemoteConnectionToExchange(string UserName, string Password, string Mailbox)
        {
                SecureString SecurePassword = new SecureString();

                string str_password = Password;
                string str_username = UserName;

                foreach (char x in str_password)
                {
                    SecurePassword.AppendChar(x);
                }

                PSCredential cred = new PSCredential(str_username, SecurePassword);

                WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri(URL), Schema, cred);

                connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Default;

                Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo);

                PowerShell powershell = PowerShell.Create();
                PSCommand command = new PSCommand();

                command.AddCommand("New-MailContact");
                command.AddParameter("ExternalEmailAddress", "SMTP:" + Mailbox + MailExtension);
                command.AddParameter("Name", Mailbox);
                command.AddParameter("Alias", Mailbox);
                command.AddParameter("FirstName", Mailbox);
                command.AddParameter("Initials", "");
                command.AddParameter("LastName", "");
                command.AddParameter("OrganizationalUnit", OrganizationalUnit);
                command.AddParameter("DomainController", configDC);

                powershell.Commands = command;

                try
                {
                    runspace.Open();

                    powershell.Runspace = runspace;

                    powershell.Invoke();


                    return "Der Kontakt wurde Erfolgreich erstellt";
                }
                catch (Exception ex)
                {
                    ...

                }
                finally
                {
                    runspace.Dispose();
                    runspace = null;
                    powershell.Dispose();
                    powershell = null;
                }


        }

我不知道如何为ActiveDirectory创建一个Remote:/ 我需要URL和Schema String。 ActiveDirectory在http://server137.linde-wiemann.com/上? = OU = NPS,OU =服务,DC =测试公司,DC = com或LDAP:// OU = NPS,OU =服务,DC =测试公司,DC = com

每个人都可以帮助我

1 个答案:

答案 0 :(得分:0)

我发现这个关于活动目录的代码是这个链接,它显示了几乎所有关于活动目录的功能。

http://www.codeproject.com/Articles/18102/Howto-Almost-Everything-In-Active-Directory-via-C