You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Get-ADUser过滤指定子OU及无姓氏的启用AD用户?

解决AD用户查询中排除多个子OU的问题

你遇到的错误是因为添加多个OU过滤时语法不正确(比如错误连续使用Where或逻辑判断写法有误),导致PowerShell无法识别参数。以下是正确的实现方式:

方法一:正则表达式批量排除OU(效率更高)

适合一次性排除多个OU的场景:

# 定义需要排除的所有子OU完整DN
$excludedOUs = @(
    "OU=Admin accounts,OU=Users,OU=Company,DC=CompanyName,DC=local",
    "OU=service accounts,OU=Users,OU=Company,DC=CompanyName,DC=local",
    "OU=disabled accounts,OU=Users,OU=Company,DC=CompanyName,DC=local"
)

# 转义OU DN中的特殊字符,拼接成正则匹配模式
$excludePattern = ($excludedOUs | ForEach-Object { [regex]::Escape($_) }) -join '|'

# 执行查询并过滤
Get-ADUser -Filter { Enabled -eq $true } -SearchBase 'OU=Users,OU=Company,DC=CompanyName,DC=local' |
    Where-Object {
        # 排除在指定子OU内的用户
        $_.DistinguishedName -notmatch $excludePattern -and
        # 过滤姓氏为空或空白的用户
        !([string]::IsNullOrWhiteSpace($_.Surname))
    } |
    Select-Object samAccountName

方法二:循环判断排除OU(逻辑更直观)

如果不想使用正则,可通过循环逐一验证:

$excludedOUs = @(
    "OU=Admin accounts,OU=Users,OU=Company,DC=CompanyName,DC=local",
    "OU=service accounts,OU=Users,OU=Company,DC=CompanyName,DC=local",
    "OU=disabled accounts,OU=Users,OU=Company,DC=CompanyName,DC=local"
)

Get-ADUser -Filter { Enabled -eq $true } -SearchBase 'OU=Users,OU=Company,DC=CompanyName,DC=local' |
    Where-Object {
        # 检查用户是否不在任何排除的OU中
        $userInExcludedOU = $false
        foreach ($ou in $excludedOUs) {
            if ($_.DistinguishedName -like "*$ou") {
                $userInExcludedOU = $true
                break
            }
        }
        -not $userInExcludedOU -and !([string]::IsNullOrWhiteSpace($_.Surname))
    } |
    Select-Object samAccountName

关键注意事项

  • 确保$excludedOUs中的每个OU DN完全正确,否则会导致过滤失效。
  • 尽量将所有过滤条件放在同一个Where-Object块内,避免拆分多个Where命令引发语法错误。
  • 使用[string]::IsNullOrWhiteSpace()比$_.Surname -notlike "$Null"更准确,可同时过滤空值和空白字符。

内容的提问来源于stack exchange,提问作者Smoore

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 18:55:28