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

如何通过PowerShell校验AD用户输入的当前密码是否正确

AD用户自助改密PowerShell实现方案

实现原理

AD不会存储可直接读取的明文或可比对密码字段,无法通过Get-ADUser获取相关属性做校验。正确的实现逻辑是调用AD原生身份认证接口,用用户输入的当前密码尝试完成认证,认证通过即说明密码有效,再执行改密操作。

可用实现脚本

以下脚本不依赖RSAT AD模块,兼容所有已加入域的Windows设备,无需管理员权限即可运行:

# 加载.NET账号管理程序集
Add-Type -AssemblyName System.DirectoryServices.AccountManagement

# 自动获取当前设备所属域名
try {
    $domainName = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain().Name
    $principalContext = New-Object System.DirectoryServices.AccountManagement.PrincipalContext('Domain', $domainName)
}
catch {
    Write-Error "无法连接到域控,请检查域网络是否正常"
    exit 1
}

# 取当前登录的域账号名
$userName = $env:USERNAME

# 校验当前密码有效性
$currentPwdSecure = Read-Host "请输入当前账号密码" -AsSecureString
$currentPwdPlain = [System.Net.NetworkCredential]::new("", $currentPwdSecure).Password
$credentialValid = $principalContext.ValidateCredentials($userName, $currentPwdPlain)

if (-not $credentialValid) {
    Write-Error "当前密码输入错误,请重新操作"
    exit 1
}

# 输入并校验新密码
$newPwdSecure = Read-Host "请输入新密码" -AsSecureString
$confirmPwdSecure = Read-Host "请再次输入新密码确认" -AsSecureString
$newPwdPlain = [System.Net.NetworkCredential]::new("", $newPwdSecure).Password
$confirmPwdPlain = [System.Net.NetworkCredential]::new("", $confirmPwdSecure).Password

if ($newPwdPlain -ne $confirmPwdPlain) {
    Write-Error "两次输入的新密码不一致,请重新操作"
    exit 1
}

# 执行改密操作
try {
    $adUser = [System.DirectoryServices.AccountManagement.UserPrincipal]::FindByIdentity($principalContext, $userName)
    $adUser.ChangePassword($currentPwdPlain, $newPwdPlain)
    Write-Host "密码修改成功,请使用新密码登录后续业务系统" -ForegroundColor Green
}
catch {
    Write-Error "密码修改失败:$($_.Exception.Message)"
    Write-Host "常见失败原因:新密码不符合域密码复杂度要求、新密码为近期使用过的历史密码" -ForegroundColor Yellow
    exit 1
}

注意事项

  • 脚本仅支持修改当前登录用户自己的密码,无需权限提升
  • 运行设备需要已加入域,且可正常连通域控服务器
  • 新密码必须符合域设置的密码策略,包含长度、复杂度、历史密码复用限制等要求
  • 密码全程仅在内存中做临时明文转换,不会持久化存储,符合安全规范

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 04:45:04