【AD】AD域快速解锁用户及重置为默认密码

根据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
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值