使用 C# 创建名称中第一个字符为“#”的 Active Directory 组

Create Active Directory Group with '#' as the first character in its name by using C#

我想创建一个新的 Active Directory 组并使用“#”作为其名称的第一个字符。但是我收到一条异常消息,说我的 C# 代码中的 'dn' 无效。我知道 '#' 是 powershell 脚本中的特殊字符,然后我用单引号转义 '#',我的 C# 代码也不例外,新的 Active Directory 组也创建成功。但是单引号也显示在 Active Directory 的面板中。

string name = "#ABC";
public void Create(string ouPath, string name)
{
    if (!DirectoryEntry.Exists("LDAP://CN=" + name + "," + ouPath))
    {
         try
         {
            DirectoryEntry entry = new DirectoryEntry("LDAP://" + ouPath);
            DirectoryEntry group = entry.Children.Add("CN=" + name, "group");
            group.Properties["sAmAccountName"].Value = name;
            group.CommitChanges();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message.ToString());
        }
    }
    else { Console.WriteLine(path + " already exists"); }
}

enter image description here

有没有人可以帮助我创建名称中第一个字符为“#”的 Active Directory 组?

谢谢。

A # 不允许作为 DN 或 CN 的第一个字符。这是 Active Directory 的限制。

有关保留字符,请参阅 here

如链接文章末尾所述,您必须使用反斜杠 (\) 而不是单引号来转义 #
请注意,在 C# 中,字符串中的反斜杠由另一个反斜杠转义。所以你的组名字符串应该是这样的:

string name = "\#ABC"; 
string ouPath = // your ou path
Create(ouPath, name);

更新: 另一种转义保留字符的方法是通过反斜杠和十六进制 ascii 码,即 0x23 for #。所以你的例子中的字符串应该是:

string name = "\23ABC";