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

PowerShell使用Set-ADUser配置下次登录改密码及AD用户不存在报错处理问询

你的脚本逻辑确实存在问题,核心问题是没有预先校验AD账号是否存在,直接执行了修改操作,导致报错触发。

具体问题说明

  • 原if($User)判断仅校验你是否输入了内容,只要输入不为空就会进入执行分支,完全没有判断该账号在AD中是否存在
  • 你直接对输入的账号执行Set-ADUser操作,当账号不存在时,命令会直接抛出系统级错误,不会走到你写的else分支
  • 嵌套的if($true)是恒真判断,属于冗余逻辑,没有实际作用

修正后代码

先通过Get-ADUser查询账号是否存在,捕获查询结果后再判断是否执行后续操作:

# 导入AD模块,若运行环境已预加载可删除该行
Import-Module ActiveDirectory -ErrorAction Stop

$User = Read-Host "Enter user login: "
# 先判断是否有输入内容
if ($User) {
    Write-Verbose "Searching user..." -Verbose
    # 查询AD用户,禁止报错输出,查询结果赋值给变量
    $adUser = Get-ADUser -Identity $User -ErrorAction SilentlyContinue
    # 判断用户是否存在
    if ($adUser) {
        # 存在则执行修改逻辑
        Set-ADUser -Identity $User -ChangePasswordAtLogon $true
        Set-ADUser -Identity $User -ChangePasswordAtLogon $false
        
        # 输出用户属性,指定需要的属性即可,无需查询所有属性提升效率
        Get-ADUser -Identity $User -Properties accountexpirationdate, accountexpires, accountlockouttime, badlogoncount, padpwdcount, lastbadpasswordattempt, lastlogondate, lockedout, passwordexpired, passwordlastset, pwdlastset | 
        Select-Object accountexpirationdate, accountexpires, accountlockouttime, badlogoncount, padpwdcount, lastbadpasswordattempt, lastlogondate, lockedout, passwordexpired, passwordlastset, pwdlastset | 
        Format-List

        Write-Verbose "Password extended!" -Verbose
    }
    else {
        # 查询结果为空则输出不存在提示
        Write-Host "User doesn't exist!"
    }
}
else {
    Write-Host "No user login input!"
}
pause

运行注意事项

脚本需要在安装了AD管理工具的环境运行,且运行账号需要有AD用户的修改权限。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 06:45:04