WMI retrieve groups that a user is member of?

2020-07-24 04:16发布

问题:

this is my code for retrieving My local Computer Info :

        ManagementObjectSearcher Usersearcher = new ManagementObjectSearcher("SELECT * FROM Win32_ComputerSystem");
        ManagementObjectCollection Usercollection = Usersearcher.Get();
        string[] sep = { "\\" };
        string[] UserName = Usercollection.Cast<ManagementBaseObject>().First()["UserName"].ToString().Split(sep, StringSplitOptions.None);

        ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_UserAccount where Domain = 'MyDomain' and Name= '" + UserName[1] + "'");
        ManagementObjectCollection collection = searcher.Get();
        WriteOnListBox("UserName: " + (string)collection.Cast<ManagementBaseObject>().First()["Name"]);
        WriteOnListBox("Full Name: " + (string)collection.Cast<ManagementBaseObject>().First()["FullName"]);
        WriteOnListBox("Description: " + (string)collection.Cast<ManagementBaseObject>().First()["Description"]);

But I I couldnt retrieve The groups I'm in and The Email.

回答1:

After a couple of hours on working on it I solved it and I Will answer My question,

private string GetGroupsForUser(string UserName)
    {
        ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_GroupUser where PartComponent=\"Win32_UserAccount.Domain='MyDomain',Name='" + UserName + "'\"");
        StringBuilder strGroups = new StringBuilder();

        foreach (ManagementObject mObject in searcher.Get())
        {
            ManagementPath path = new ManagementPath(mObject["GroupComponent"].ToString());

            if (path.ClassName == "Win32_Group")
            {
                String[] names = path.RelativePath.Split(',');
                strGroups.Append(names[1].Substring(names[1].IndexOf("=") + 1).Replace('"', ' ').Trim() + ", ");
            }
        }
        return strGroups.ToString();
    }


标签: c# wmi