使用PowerShell在数组中实现通配符匹配,排除系统账户执行AD查询
我来帮你搞定这个问题!看起来你已经理清了核心逻辑——从包含用户全名的列表里筛掉系统账户,再执行Active Directory查询。咱们可以通过通配符匹配精准过滤数组,下面给你一套可落地的实现方案,结合常用的PowerShell和C#两种场景:
解决方案:通配符过滤+AD查询
一、PowerShell实现(最常用的AD操作方式)
1. 核心思路
先定义系统账户的通配符匹配规则,过滤掉原始列表中符合规则的条目,再对剩余名单执行AD查询。
# 你的原始用户全名列表 $fullNames = @("John Doe", "Jane Smith", "SQL Service Account", "Domain Admin", "Bob Johnson", "Print System Account") # 自定义系统账户的通配符匹配规则(根据你的实际命名规则调整) $systemAccountPatterns = @("*Service*", "*System*", "*Admin", "SVC-*") # 过滤掉匹配系统账户模式的条目 $filteredNames = $fullNames | Where-Object { # 检查当前全名是否不匹配任何系统账户规则 -not ($systemAccountPatterns | Where-Object { $_ -like $_ }) } # 对过滤后的名单执行AD查询 foreach ($name in $filteredNames) { try { # 安全的Filter写法,自动处理特殊字符转义 $adUser = Get-ADUser -Filter { Name -eq $name } -Properties SamAccountName, EmailAddress Write-Output "✅ 找到AD账户: $($adUser.Name) | 账号: $($adUser.SamAccountName) | 邮箱: $($adUser.EmailAddress)" } catch { Write-Warning "⚠️ 无法找到用户: $name" } }
2. 关键说明
- 你可以完全根据公司的系统账户命名习惯修改
$systemAccountPatterns,比如系统账户都以SYS-开头,就添加"SYS-*"到数组里。 - 使用
{ Name -eq $name }这种Filter写法,PowerShell会自动处理全名中的空格、特殊字符,避免语法错误。
二、C#实现(适合嵌入业务系统)
如果你的需求是嵌入到C#应用中,可以用System.DirectoryServices.AccountManagement库实现,同时自定义通配符匹配逻辑:
using System; using System.Collections.Generic; using System.DirectoryServices.AccountManagement; using System.Linq; using System.Text.RegularExpressions; class ADUserQuery { static void Main() { // 原始用户全名列表 List<string> fullNames = new List<string> { "John Doe", "Jane Smith", "SQL Service Account", "Domain Admin", "Bob Johnson", "SYS-Backup" }; // 系统账户通配符规则 string[] systemPatterns = { "*Service*", "*System*", "*Admin", "SYS-*" }; // 过滤列表:排除匹配任何系统规则的条目 var filteredNames = fullNames.Where(name => !systemPatterns.Any(pattern => WildcardMatch(name, pattern))).ToList(); // 连接域环境执行AD查询 using (PrincipalContext domainContext = new PrincipalContext(ContextType.Domain)) { foreach (var name in filteredNames) { UserPrincipal user = UserPrincipal.FindByIdentity(domainContext, IdentityType.Name, name); if (user != null) { Console.WriteLine($"✅ 找到账户: {user.Name} | 登录名: {user.SamAccountName} | 邮箱: {user.EmailAddress}"); } else { Console.WriteLine($"⚠️ 未找到用户: {name}"); } } } } // 自定义通配符匹配方法(将*转为正则的.*,?转为.) static bool WildcardMatch(string input, string pattern) { string regexPattern = "^" + Regex.Escape(pattern).Replace("\\*", ".*").Replace("\\?", ".") + "$"; return Regex.IsMatch(input, regexPattern, RegexOptions.IgnoreCase); } }
内容的提问来源于stack exchange,提问作者cyborgcommando0
相关产品推荐
相关产品推荐

