使用wmi列出域用户

时间:2014-01-21 20:13:19

标签: windows dns c# wmi

我想在C#中列出使用WMI的Windows域的所有用户。

有人可以帮助我吗?

这是我的代码:

try
            {
                ConnectionOptions connection = new ConnectionOptions();
                connection.Username = user;
                connection.Authority = "ntlmdomain:" + domain;
                connection.Password = pwd;

                SelectQuery query = new SelectQuery("SELECT * FROM Win32_UserAccount");
                ManagementScope scope = new ManagementScope(@"\\FullComputerName\\root\\CIMV2", connection);
                scope.Connect();
                ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);

                foreach (ManagementObject queryObj in searcher.Get())
                {
                    Console.WriteLine("Account Type: " + queryObj["AccountType"]);
                    Console.WriteLine("Caption: " + queryObj["Caption"]);
                    Console.WriteLine("Description: " + queryObj["Description"]);
                    Console.WriteLine("Disabled: " + queryObj["Disabled"]);
                    Console.WriteLine("Domain: " + queryObj["Domain"]);
                    Console.WriteLine("Full Name: " + queryObj["FullName"]);
                    Console.WriteLine("Local Account: " + queryObj["LocalAccount"]);
                    Console.WriteLine("Lockout: " + queryObj["Lockout"]);
                    Console.WriteLine("Name: " + queryObj["Name"].ToString());
                    Console.WriteLine("Password Changeable: " + queryObj["PasswordChangeable"]);
                    Console.WriteLine("Password Expires: " + queryObj["PasswordExpires"]);
                    Console.WriteLine("Password Required: " + queryObj["PasswordRequired"]);
                    Console.WriteLine("SID: " + queryObj["SID"]);
                    Console.WriteLine("SID Type: " + queryObj["SIDType"]);
                    Console.WriteLine("Status: " + queryObj["Status"]);
                    Console.WriteLine("");
                }
            }
            catch (ManagementException err)
            {
                Console.WriteLine("An error occured while querying for WMI data: " + err.Message);
            }
            catch (System.UnauthorizedAccessException unauthorizedErr)
            {
                Console.WriteLine("Connection error " + "(user name or password might be incorrect): " + unauthorizedErr.Message);
            }

1 个答案:

答案 0 :(得分:0)

ManagementScope构造函数中的命名空间路径中存在拼写错误:

ManagementScope scope = new ManagementScope(@"\\FullComputerName\\root\\CIMV2", connection);

字符串应为@"\\FullComputerName\root\CIMV2""\\\\FullComputerName\\root\\CIMV2"

请注意,您无法为本地连接指定用户帐户。因此,如果FullComputerName是本地计算机,请改用:

ManagementScope scope = new ManagementScope("root\\CIMV2");