WMI retrieve groups that a user is member of?

ぐ巨炮叔叔 提交于 2019-12-21 21:27:45

问题


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();
    }


来源:https://stackoverflow.com/questions/4794624/wmi-retrieve-groups-that-a-user-is-member-of

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!