Search code examples
c#.netwmi

WMI Query to get enabled user accounts. What is wrong with my WHERE clause?


I am trying to get a list of non-disabled user accounts on the local computer with SID values for each user. I could not make this work with the DirectoryEntry class because the returned users all had NULL in the ObjectSecurity field. So I tried to use ManagementObjectSearcher

SelectQuery sQuery = new SelectQuery("Win32_UserAccount"); );
var searcher = new ManagementObjectSearcher(sQuery);

The returned users have the information I need but this query gives me disabled accounts. I'd like to add a WHERE clause to account for that but I can't get it right.

I've tried

new SelectQuery("Win32_UserAccount WHERE NOT Disabled");
new SelectQuery("Win32_UserAccount WHERE Disabled='False'");
new SelectQuery("Win32_UserAccount WHERE Disabled=False");

All of these cause an exception. Can someone tell me how to word this?


Solution

  • You're not using SearchQuery correctly; to specify a condition, you have to either give a full query string, or use the SearchQuery(String, String) constructor that takes the query separately:

    var query = new SelectQuery("SELECT * FROM Win32_UserAccount WHERE Disabled=False");
    var searcher = new ManagementObjectSearcher(query);
    

    OR

    var query = new SelectQuery("Win32_UserAccount", "Disabled=False");
    var searcher = new ManagementObjectSearcher(query);
    

    However, you can simplify your code by using the ManagementObjectSearcher(String) constructor that takes a query string directly:

    var searcher = new ManagementObjectSearcher("SELECT * FROM Win32_UserAccount WHERE Disabled=False");