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

PowerShell脚本筛选AD用户问题:无法排除含noreply邮箱的账号

AD用户密码过期排查脚本问题解决思路

问题根源分析

你的脚本无法排除带noreply邮箱的账号,主要有三个核心问题:

  1. 属性拼写错误:脚本里写的EmailAdress少了一个字母d,正确属性名是EmailAddress。拼写错误会导致该属性值为$null,$null -notcontains 'noreply*'永远为$true,等于没加任何排除条件。
  2. 运算符使用错误:-contains/-notcontains是用来判断集合是否包含精确值的,不支持通配符匹配。要匹配包含noreply的邮箱,必须用-like/-notlike运算符。
  3. 密码过期判断逻辑不准确:仅用PasswordLastSet和$CutOffDate比较,忽略了不同用户可能有不同的密码有效期策略,容易出现误判。AD自带msDS-UserPasswordExpiryTimeComputed属性,可以直接获取计算好的密码过期时间,结果更准确。

修正后的脚本

# 计算两周后的时间,用于判断密码是否在两周内过期
$twoWeeksLater = (Get-Date).AddDays(14)

foreach($OU in $OUs) {
    # 仅获取需要的属性,避免拉取所有AD属性拖慢运行速度
    $Users = Get-ADUser -SearchBase $OU -Filter * -Properties EmailAddress, msDS-UserPasswordExpiryTimeComputed, PasswordNeverExpires
    
    foreach($User in $Users) {
        # 直接跳过密码永不过期的账号(服务账号常用配置)
        if ($User.PasswordNeverExpires) {
            continue
        }
        
        # 将AD的文件时间格式转换为DateTime类型,处理未设置密码的异常情况
        $expiryTime = if ($User.'msDS-UserPasswordExpiryTimeComputed') {
            [DateTime]::FromFileTime($User.'msDS-UserPasswordExpiryTimeComputed')
        } else {
            continue
        }
        
        # 判断密码是否在两周内过期,且邮箱不包含noreply关键字
        if ($expiryTime -lt $twoWeeksLater -and $User.EmailAddress -notlike '*noreply*') {
            Write-Host $User.EmailAddress
        }
    }
}

额外优化建议

  • 提前过滤减少处理量:可以把排除条件整合到Get-ADUser的Filter里,减少后续循环需要处理的用户数量,示例:
    $filter = "PasswordNeverExpires -eq `$false -and EmailAddress -notlike '*noreply*'"
    $Users = Get-ADUser -SearchBase $OU -Filter $filter -Properties msDS-UserPasswordExpiryTimeComputed
    
  • 禁止使用-properties *:拉取所有AD属性会大幅降低脚本运行效率,只指定业务需要的属性即可。
  • 补充异常处理:针对未设置邮箱、未设置密码的账号增加判断,避免脚本出现非预期报错。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 20:22:20