在远程机器上检索 LoggedOnUsers

Retrieve LoggedOnUsers on Remote Machine

我正在构建一个 C# 应用程序以使用 WMI 和 WQL 查询监视服务器和工作站工作负载。我正在使用 WMI,因为与 powershell 查询相比,它似乎更快。当我尝试检索远程计算机上的登录用户时,我的困难就开始了。我想我需要使用 Win32_LoggedOnUser class。我尝试了以下查询:

@"SELECT * FROM Win32_LoggedOnUser"
@"SELECT Antecedent FROM Win32_LoggedOnUser"

我习惯的是像这样检索所需的值:

var cims = connection.getCimInstances(this, queryUser);

 if (cims != null)
 {
    foreach (CimInstance cim in cims)
    {
      Komponenten.User user = new Komponenten.User();
      user.Name = Convert.ToString(cim.CimInstanceProperties["Name"].Value);
                    users.Add(user);
    }
 }    

其中 queryUser 是上面的字符串之一。

在这两种情况下,我在 return 中得到了一个 Win32_Account 对象,这似乎表明——并且调试器似乎证实了——我应该再次在 returned Win32_Account class 上使用 CimInstanceProperties["Name"].Value。但这根本不起作用。关于如何访问存储在 CimInstanceProperity 中的 Win32_Account 的 CimInstanceProperties 的任何想法?我在各自的 Windows 参考页面 (https://docs.microsoft.com/en-us/windows/win32/cimwin32prov/win32-loggedonuser) 和广泛的 google 搜索中都找不到任何内容。

谢谢!

我最终使用 ManagementObject-ClassRegex 在转换 Antecedent - 对象到字符串:

var users = new List<Komponenten.User>();
        var searcher = this.connection.makeQuery(this, "SELECT * FROM Win32_LoggedOnUser");

        if (searcher != null)
        {
            foreach (ManagementObject queryObj in searcher.Get())
            {
                Komponenten.User user = new Komponenten.User();
                var win32_account = queryObj["Antecedent"].ToString();
                string stripped = Regex.Replace(win32_account, "[^a-zA-Z=]+", "", RegexOptions.Compiled);
                int end = stripped.LastIndexOf("=");
                user.Name = stripped.Substring(end+1);
                users.Add(user);
            }

            this.users = users;

考虑到 LogonSession 的替代方案是:

var users = new List<Komponenten.User>();
        var searcher = this.connection.makeQuery(this, "SELECT LogonId  FROM Win32_LogonSession Where LogonType=2");
        var Scope = this.connection.getScope(this, this.connection.getConnection());

        if (searcher != null)
        {
            foreach (ManagementObject queryObj in searcher.Get())
            {
                ObjectQuery LQuery = new ObjectQuery("Associators of {Win32_LogonSession.LogonId=" + queryObj["LogonId"] + "} Where AssocClass=Win32_LoggedOnUser Role=Dependent");
                ManagementObjectSearcher LSearcher = new ManagementObjectSearcher(Scope, LQuery);
                foreach (ManagementObject LWmiObject in LSearcher.Get())
                {
                    Komponenten.User user = new Komponenten.User();
                    user.Name =  Convert.ToString(LWmiObject["Name"]);
                    users.Add(user);
                }
            }
            this.users = users;
        }

其中 this.connection.getConnectionConnectionsOption 对象,具体取决于您各自的域和帐户数据