Click here to Skip to main content
Licence CPOL
First Posted 9 Jan 2008
Views 41,064
Downloads 316
Bookmarked 25 times

Enumerating Users using WMI.NET and C#

By | 9 Jan 2008 | Article
Enumerate all the available users, groups using WMI.NET and C#

Introduction

Recently, I had to get all the user names in my local machine. I was searching for a proper method and it was really hard to get one. I knew I have to use WMI, but the biggest obstacle was of combining different WMI queries to get the result.

Background

The WMI classes that immediately came into my mind were as listed below:

Each of the classes has its own use. However, Win32_Account forms the main class and other classes derive Win32_Account.

Using the Code

To get all user accounts, you could just query:

select * from Win32_UserAccount where Domain=’YOURDOMAIN’

And to get all groups, you could just query:

select * from Win32_GroupUser where Domain=’YOURDOMAIN’

Using C# for user accounts:

public static void GetUsers()
{
     SelectQuery sQuery = new SelectQuery(“Win32_UserAccount”,“Domain=’CHAKS-PC’”);

     try
     {
            ManagementObjectSearcher mSearcher = new ManagementObjectSearcher(sQuery);

            Console.WriteLine(“User Accounts”);
            Console.WriteLine(“”);

            foreach (ManagementObject mObject in mSearcher.Get())
            {
                Console.WriteLine(mObject[“Name”]);
            }
      }
      catch (Exception ex)
      {
            Console.WriteLine(ex.ToString());
      }

     Console.ReadKey();
 }

Using C# for groups:

public static void GetGroups()
 {
       SelectQuery sQuery = new SelectQuery(“Win32_Group”, “Domain=’CHAKS-PC’”);

       try
       {
             ManagementObjectSearcher mSearcher = new ManagementObjectSearcher(sQuery);

             Console.WriteLine(“Groups”);
             Console.WriteLine(“”);

             foreach (ManagementObject mObject in mSearcher.Get())
             {
                 Console.WriteLine(mObject[“Name”]);
             }
        }
        catch (Exception ex)
        {
             Console.WriteLine(ex.ToString());
        }

        Console.ReadKey();
 }

Now to get users corresponding to a particular group, we need to query Win32_GroupUser and there comes the trick.

The Win32_GroupUser is an association class and relates a group and the account to which that is a member of that group.

So, now our query changes to:

select * from Win32_GroupUser where _
    GroupComponent=’”‘Win32_Group.Domain=’domain-name’,Name=’group-name””‘

And our C# code changes to:

public static void GetUsers(String DomainName, String GroupName)
{
      #region Build WMI query using SelectQuery
      ///<summary>
      /// Alternate method for building query
      /// Which I think is better approach
      ///</summary>
      StringBuilder sBuilder = new StringBuilder(“GroupComponent=”);
      sBuilder.Append(‘”‘);
      sBuilder.Append(“Win32_Group.Domain=”);
      sBuilder.Append(“‘”);
      sBuilder.Append(DomainName);
      sBuilder.Append(“‘”);
      sBuilder.Append(“,Name=”);
      sBuilder.Append(“‘”);
      sBuilder.Append(GroupName);
      sBuilder.Append(“‘”);
      sBuilder.Append(‘”‘);
      SelectQuery sQuery = new SelectQuery(“Win32_GroupUser”, sBuilder.ToString());
      #endregion           

      ///<summary>
      /// Execute the query
      /// Construct a ManagementPath from the PartComponent and check for ClassName
      /// and extract the UserName
      /// Depending on which method you used to build the query,
      /// pass the String or SelectQuery object to ManagementObjectSearcher
      ///</summary>
      try
      {
            ManagementObjectSearcher mSearcher = new ManagementObjectSearcher(sQuery);
            foreach (ManagementObject mObject in mSearcher.Get())
            {
                 ManagementPath path = 
                        new ManagementPath(mObject[“PartComponent”].ToString());
                 if (path.ClassName == “Win32_UserAccount”)
                 {
                      String[] names = path.RelativePath.Split(‘,’);
                      Console.WriteLine(names[1].Substring(names[1].IndexOf(“=”) 
                            + 1).Replace(‘”‘, ‘ ‘).Trim());
                 }
            }
      }
      catch (Exception ex)
      {
            Console.WriteLine(ex.ToString());
      }

      Console.ReadKey();
}

Hope you enjoyed reading my article.

If you have any queries, please do email me or start a discussion below.

History

  • 10th January, 2008 - Initial post

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

chakkaradeepcc

Software Developer

New Zealand New Zealand

Member

Chakkaradeep, known as Chaks to his friends, hails from the Indian subcontinent.Having done his Masters in Software Engineering, he knows his way around a computer and has sound knowledge of Microsoft technologies.
 
Chaks is currently working as a Microsoft Developer @ New Zealand.
 
You can reach him via his blog - http://chakkaradeep.wordpress.com

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralGroups for a user: code works but is very slow! Pinmemberkenshiro20005:07 14 Apr '08  
GeneralRe: Groups for a user: code works but is very slow! PinmemberMurali Krishna Babu18:28 22 Nov '10  
Generalno update if we change the the users accounts name, please help PinmemberMember 407499315:11 22 Mar '08  
GeneralRe: no update if we change the the users accounts name, please help Pinmemberchakkaradeepcc0:51 27 Mar '08  
GeneralInvalid Zip file PinmemberKChandos7:32 9 Jan '08  
AnswerRe: Invalid Zip file Pinmemberchakkaradeepcc7:51 9 Jan '08  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web03 | 2.5.120517.1 | Last Updated 9 Jan 2008
Article Copyright 2008 by chakkaradeepcc
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid