// 第三种方法 : 远程注册表 -> 需要域管权限 /// <summary> /// 利用 OpenRemoteBaseKey 读取 HKEY_USERS 的键项 /// </summary> /// <param name="server"></param> /// <returns></returns> private static IEnumerable <string> GetRegistryLoggedOn(string server) { var users = new List <string>(); try { // 远程打开注册表配置单元,如果它不是我们当前的配置单元 RegistryKey key = RegistryKey.OpenRemoteBaseKey(RegistryHive.Users, server); // 找到与我们的正则表达式匹配的所有子项 var filtered = key.GetSubKeyNames().Where(sub => SidRegex.IsMatch(sub)); foreach (var subkey in filtered) { users.Add(subkey); } } catch (Exception) { yield break; } foreach (var user in users.Distinct()) { yield return(user); } }
private static (string UserPrincipalName, string ActiveDirectorySid) ParseSidOrUpn(string text) { var isSid = SidRegex.IsMatch(text); var userPrincipalName = isSid ? null : text; var activeDirectorySid = isSid ? text : null; return(userPrincipalName, activeDirectorySid); }