开发者

WMI retrieve groups that a user is member of?

开发者 https://www.devze.com 2023-02-06 10:20 出处:网络
this is my code for retrieving My local Computer Info : 开发者_运维技巧ManagementObjectSearcher Usersearcher = new ManagementObjectSearcher(\"SELECT * FROM Win32_ComputerSystem\");

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.


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

精彩评论

暂无评论...
验证码 换一张
取 消