C# 在 Active Directory 中创建 OU

标签 c# active-directory

我正在努力使用下面的代码为 Active Directory 创建一个 OU。

strPath = "OU=TestOU,DC=Internal,DC=Com"

DirectoryEntry objOU; 
objOU = ADentry.Children.Add(strPath, "OrganizationalUnit");
objOU.CommitChanges();

问题是 strPath 包含完整路径 'OU=TestOU,DC=Internal,DC=net' 所以使用 .Children.Add 使 ldap 路径 'OU=TestOU,DC=Internal,DC=net,DC= Internal,DC=net' 这会导致错误,因为该域显然不存在。

我的问题是我可以使用 strPath 而不使用 .Children.Add 创建 OU 吗?

我不熟悉 AD,这是我从我之前的人那里继承的。

最佳答案

试试这个

using System;
using System.DirectoryServices;

namespace ADAM_Examples
{
    class CreateOU
    {
        /// <summary>
        /// Create AD LDS Organizational Unit.
        /// </summary>
        [STAThread]
        static void Main()
        {
            DirectoryEntry objADAM;  // Binding object.
            DirectoryEntry objOU;    // Organizational unit.
            string strDescription;   // Description of OU.
            string strOU;            // Organiztional unit.
            string strPath;          // Binding path.
        // Construct the binding string.
        strPath = "LDAP://localhost:389/O=Fabrikam,C=US";

        Console.WriteLine("Bind to: {0}", strPath);

        // Get AD LDS object.
        try
        {
            objADAM = new DirectoryEntry(strPath);
            objADAM.RefreshCache();
        }
        catch (Exception e)
        {
            Console.WriteLine("Error:   Bind failed.");
            Console.WriteLine("         {0}", e.Message);
            return;
        }

        // Specify Organizational Unit.
        strOU = "OU=TestOU";
        strDescription = "AD LDS Test Organizational Unit";
        Console.WriteLine("Create:  {0}", strOU);

        // Create Organizational Unit.
        try
        {
            objOU = objADAM.Children.Add(strOU,
                "OrganizationalUnit");
            objOU.Properties["description"].Add(strDescription);
            objOU.CommitChanges();
        }
        catch (Exception e)
        {
            Console.WriteLine("Error:   Create failed.");
            Console.WriteLine("         {0}", e.Message);
            return;
        }

        // Output Organizational Unit attributes.
        Console.WriteLine("Success: Create succeeded.");
        Console.WriteLine("Name:    {0}", objOU.Name);
        Console.WriteLine("         {0}",
            objOU.Properties["description"].Value);
        return;
    }
}
}

关于C# 在 Active Directory 中创建 OU,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/400691/

相关文章:

c# - protobuf-net 不序列化 List<T>

c# - resharper 协变数组转换 - 矛盾修复

c# - UserPrincipals.GetAuthorizationGroups 枚举组时发生错误 (1301)。升级到 Server 2012 域 Controller 后

windows - Win32 : How to validate credentials against Active Directory?

c# - 使使用 SQLiteConnection 的方法更加可重用

c# - Automapper 将 List<type> 的 int 属性值映射到 List<int>

c# - .NET Linq 左连接

php ldap-bind 密码过期

c# - 如何确保 IsInRole 检查不使用缓存的凭据

email - Get-AdUser 其中邮件不为空