从Active Directory组中获取用户,其中组名之间有空格

时间:2018-07-03 10:37:40

标签: c# active-directory

我正在搜索广告组“ PT运动联络中心团队(印度)”

我使用的代码是

using System;
using System.IO;
using System.DirectoryServices.AccountManagement;
using System.Text;

namespace GetUserInAGroup
{
    class Program
    {
        static void Main(string[] args)
        {
            string groupName = string.Empty;
            string domainName = string.Empty;
            StringBuilder data=new StringBuilder();
            Console.WriteLine("Group Name");
             groupName = "PT Sport Contact Centre Team (India)"; //Console.ReadLine();
             domainName = "ad.MyDomain.com";

            PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainName);
            GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, groupName);

            if (grp != null)
            {
                foreach (Principal p in grp.GetMembers(true))
                {
                    data.Append(p.Name + '|' + p.UserPrincipalName + '|' + p.SamAccountName + '|' + groupName + System.Environment.NewLine);
                    //Console.WriteLine(p.Name +'|' + p.UserPrincipalName + '|' + p.SamAccountName); //You can add more attributes, samaccountname, UPN, DN, object type, etc... 
                }

                Console.WriteLine(data.ToString());
                grp.Dispose();
                ctx.Dispose();
                domainName = Console.ReadLine();
                using (StreamWriter outfile =new StreamWriter(@"D:\Temp" + @"\" + groupName + ".txt"))
                {
                    outfile.Write(data.ToString());
                }
            }
            else
            {
                Console.WriteLine("\nWe did not find that group in that domain, perhaps the group resides in a different domain?");
            }
        }
    }
}

可能由于空格而无法找到该组,或者可能是方括号。请有人帮忙。

0 个答案:

没有答案