Ermittelt alle Gruppenmitgliedschaften eines Users auf einem Remotesystem
using System.Collections.Generic;
using System.Management;
/// <summary>
/// Ermittelt alle Gruppenmitgliedschaften eines Users auf einem Remotesystem
/// </summary>
/// <param name="ComputerName"></param>
/// <param name="UserName"></param>
/// <returns></returns>
public static Dictionary<string, string> GetLocalGroupMemberShip(string ComputerName, string UserName)
{
Dictionary<string, string> LocalGroups = new Dictionary<string, string>();
ManagementObjectSearcher mos = new ManagementObjectSearcher("SELECT * FROM Win32_Group WHERE LocalAccount = TRUE");
ManagementScope ms = new ManagementScope("\\\\" + ComputerName + "\\root\\cimv2");
mos.Scope = ms;
try
{
mos.Scope.Connect();
}
catch (Exception)
{
return null;
}
foreach (ManagementObject mo in mos.Get())
{
ManagementObjectSearcher userSearcher = new ManagementObjectSearcher("SELECT * FROM Win32_GroupUser Where GroupComponent = \"Win32_Group.Domain=\'" + ComputerName + "\',Name=\'" + mo["Name"] + "\'\"");
userSearcher.Scope = ms;
try
{
userSearcher.Scope.Connect();
foreach (ManagementObject userObject in userSearcher.Get())
{
string UName = userObject["PartComponent"].ToString();
UName = UName.Substring(UName.IndexOf("=") + 1);
string Domain = UName.Substring(0, UName.IndexOf((","))).Replace("\"", "");
UName = UName.Substring(UName.IndexOf("=") + 1).Replace("\"", "");
if (UName.IndexOf(UserName, 0, StringComparison.OrdinalIgnoreCase) == 0)
LocalGroups.Add(mo["Name"].ToString(), Domain + "\\" + UName);
}
}
catch (Exception)
{
}
}
return LocalGroups;
}
Kommentare zum Snippet