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

PowerShell中Get-ADUser结合数组变量排除多用户问题

PowerShell脚本排除多个AD用户的问题解决

问题场景

我正在修改PowerShell脚本,用来筛选满足以下条件的AD用户:

  • 超过$ENV:UserAge天未登录
  • 账户处于启用状态
  • 排除指定的用户列表

当前脚本单个排除用户正常,但设置多用户数组时,无法排除目标用户。原脚本如下:

$ENV:UserAge = 90
$ENV:Excluded = ("guest@domain.local")
$age = (get-date).AddDays(-$ENV:UserAge)
$OldUsers = Get-ADuser -Filter * -properties UserPrincipalName, Enabled, WhenCreated, LastLogonDate |
     select UserPrincipalName, Enabled, WhenCreated, LastLogonDate |
     Where-Object { ($_.LastLogonDate -lt $age -and $_.LastLogonDate -gt $null) -and ($_.Enabled -eq $True) -and ($_.UserPrincipalName -gt $Null) -notmatch ($_.UserPrincipalName -in $Env:Excluded ) }

当设置$ENV:Excluded = ("guest@domain.local", "test@domain.local")时,结果仍包含这两个应排除的用户。


问题根源

脚本里的-notmatch用错了场景:-in运算符返回的是布尔值(True/False),而-notmatch是字符串正则匹配运算符,把布尔值传给它会导致逻辑判断失效。正确的写法应该是用-not直接取反-in的结果。


解决方案

方案一:修正Where-Object逻辑

直接调整过滤条件的逻辑写法,就能实现多用户排除:

$ENV:UserAge = 90
$ENV:Excluded = ("guest@domain.local", "test@domain.local")
$age = (Get-Date).AddDays(-$ENV:UserAge)
$OldUsers = Get-ADUser -Filter * -Properties UserPrincipalName, Enabled, WhenCreated, LastLogonDate |
    Select-Object UserPrincipalName, Enabled, WhenCreated, LastLogonDate |
    Where-Object { 
        ($_.LastLogonDate -lt $age -and $_.LastLogonDate -ne $null) -and 
        $_.Enabled -eq $true -and 
        $_.UserPrincipalName -ne $null -and
        -not ($_.UserPrincipalName -in $ENV:Excluded)
    }

方案二:在AD查询阶段直接过滤(更高效)

上面的方法是先拉取所有AD用户再过滤,大域环境下效率较低。可以直接在Get-ADUser的-Filter参数里整合所有条件,让AD服务端提前过滤数据:

$ENV:UserAge = 90
$ENV:Excluded = ("guest@domain.local", "test@domain.local")
$age = (Get-Date).AddDays(-$ENV:UserAge)

# 构建排除用户的Filter条件
$excludeFilter = ($ENV:Excluded | ForEach-Object { "UserPrincipalName -ne '$_'" }) -join " -and "

$OldUsers = Get-ADUser -Filter "Enabled -eq `$true -and LastLogonDate -lt `$age -and LastLogonDate -ne `$null -and $excludeFilter" `
    -Properties UserPrincipalName, Enabled, WhenCreated, LastLogonDate |
    Select-Object UserPrincipalName, Enabled, WhenCreated, LastLogonDate

额外说明

  • 把$_.LastLogonDate -gt $null改成$_.LastLogonDate -ne $null,更符合PowerShell的常规写法。
  • 方案二通过服务端过滤,能减少返回的数据量,查询速度更快,适合用户量较大的AD环境。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.14 15:55:04