1
すべてのローカルグループとその尊敬すべきメンバーのコレクションを作成しようとしていますが、リストされたコードで挑戦しているのは、 "Administrators"グループのメンバーが空で、管理者ではなくメンバを返します。何か案は?ローカルグループのメンバーを一覧表示する
private void BuildGroupMembership(string remoteHost, string targetdomain, string userName, string password, bool domainOnly)
{
var groupsList = new List<string>();
PrincipalContext pContext = null;
PrincipalContext searchContext = null;
if (string.IsNullOrEmpty(remoteHost))
{
remoteHost = Environment.MachineName;
}
if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
{
pContext = new PrincipalContext(ContextType.Machine, remoteHost, null, ContextOptions.Negotiate, userName, password);
searchContext = new PrincipalContext(ContextType.Domain, targetdomain, null, ContextOptions.Negotiate, userName, password);
}
else
{
pContext = new PrincipalContext(ContextType.Machine, remoteHost, null, ContextOptions.Negotiate);
searchContext = new PrincipalContext(ContextType.Domain, targetdomain, null, ContextOptions.Negotiate);
}
try
{
var pSearcher = new PrincipalSearcher(new GroupPrincipal(pContext));
foreach (var principal in pSearcher.FindAll().Where(principal => !groupsList.Contains(principal.Name))) groupsList.Add(principal.Name);
foreach (var group in groupsList)
try
{
var groupItem = new Group {GroupName = group};
Groups.Add(groupItem);
var grp = GroupPrincipal.FindByIdentity(pContext, group);
if (grp != null)
{
var allmembers = grp.GetMembers(false).ToList();
var members = domainOnly ? allmembers.Where(x => x.ContextType == ContextType.Domain).ToList() : allmembers.ToList();
foreach (var p in members)
try
{
var adGroup = GroupPrincipal.FindByIdentity(searchContext, IdentityType.Sid, p.Sid.Value);
if (adGroup != null)
{
groupItem.GroupMembers.Add(new GroupMember
{
MemberDomain = adGroup.DistinguishedName.Substring(adGroup.DistinguishedName.IndexOf("DC="), adGroup.DistinguishedName.Length - adGroup.DistinguishedName.IndexOf("DC=")).Replace("DC=", "").Replace(",", "."),
MemberName = p.SamAccountName,
MemberSID = p.Sid.ToString(),
IsGroup = true
});
continue;
}
var adUser = UserPrincipal.FindByIdentity(searchContext, IdentityType.Sid, p.Sid.ToString());
if (adUser != null)
{
groupItem.GroupMembers.Add(new GroupMember
{
MemberDomain = adUser.DistinguishedName.Substring(adUser.DistinguishedName.IndexOf("DC="), adUser.DistinguishedName.Length - adUser.DistinguishedName.IndexOf("DC=")).Replace("DC=", "").Replace(",", "."),
MemberName = p.SamAccountName,
MemberSID = p.Sid.ToString(),
IsGroup = false
});
}
}
catch
{
// ignored
}
grp.Dispose();
}
}
catch
{
}
pContext.Dispose();
searchContext.Dispose();
}
catch (COMException ex)
{
throw new AuthenticationException(ex.Message);
}
}