根据AD域管理中心返回的powershell指令,再通过拷打GPT做了一个能用的
检测有两种,一种是CN,即显示名
还有一种是登录账户,即SAMAccountName
只需要修改【$NewPassword】即可
效果图
# 确保 Active Directory 模块已导入
Import-Module ActiveDirectory
# 提示用户输入查询条件
$inputValue = Read-Host "请输入工号或者姓名"
# 检查是否输入了有效的值
if ([string]::IsNullOrWhiteSpace($inputValue)) {
Write-Host "错误:未输入有效的查询信息。" -ForegroundColor Red
exit
}
# 定义新密码
$NewPassword = "123456"
# 设置服务器变量:计算机名 + 域名
$Server = "$env:COMPUTERNAME.$env:USERDNSDOMAIN"
# 判断输入是否包含中文字符
if ($inputValue -match "[\u4e00-\u9fa5]") {
# 如果包含中文字符,按 CN (Name) 查找
Write-Host "检测到姓名,按 CN (Name) 查找..." -ForegroundColor Cyan
try {
$user = Get-ADUser -Filter {Name -eq $inputValue} -Properties DistinguishedName
if ($user) {
Write-Host "找到用户: $($user.Name)"
$Identity = $user.DistinguishedName
Write-Host "所在 OU: $Identity"
} else {
Write-Host "未找到名称为 '$inputValue' 的用户。" -ForegroundColor Yellow
exit
}
}
catch {
Write-Host "查询出错: $_" -ForegroundColor Red
exit
}
}
else {
# 如果不包含中文字符,按 SAMAccountName 查找
Write-Host "检测到工号输入,按 SAMAccountName 查找..." -ForegroundColor Cyan
try {
$user = Get-ADUser -Identity $inputValue -Properties DistinguishedName
if ($user) {
Write-Host "找到用户: $($user.Name)"
$Identity = $user.DistinguishedName
Write-Host "所在 OU: $Identity"
} else {
Write-Host "未找到 SAMAccountName 为 '$inputValue' 的用户。" -ForegroundColor Yellow
exit
}
}
catch {
Write-Host "查询出错: $_" -ForegroundColor Red
exit
}
}
# 重置用户密码
try {
Write-Host "正在重置用户密码..." -ForegroundColor Cyan
Set-ADAccountPassword -Identity $Identity -NewPassword (ConvertTo-SecureString $NewPassword -AsPlainText -Force) -Reset:$true -Server $Server
Write-Host "密码已成功重置为 '$NewPassword'" -ForegroundColor Green
}
catch {
Write-Host "密码重置失败: $_" -ForegroundColor Red
}
# 解锁用户账户
try {
Write-Host "正在解锁用户账户..." -ForegroundColor Cyan
Unlock-ADAccount -Identity $Identity -Server $Server
Write-Host "用户账户已成功解锁。" -ForegroundColor Green
}
catch {
Write-Host "用户账户解锁失败: $_" -ForegroundColor Red
}