批量去掉指定域用户姓名中的“2”后缀-powershell脚本

遇到一个需求,需求批量修改ad域中的指定账号姓名,去末尾的“2”。这个操作实际修改了3个字段:displayName, givenName, name。

例如:域账号:LLQQ1112,姓名:张三2,修改后的姓名:张三。

powershell脚本如下:

<code>Import-Module ActiveDirectory

# 指定包含AD域账号的txt文件路径
$userListFile = "C:\group\123list.txt"

# 读取txt文件中的域账号
$users = Get-Content $userListFile

# 遍历每个域账号
foreach ($user in $users) {
    try {
        # 获取域账号的AD对象
        $adUser = Get-ADUser -Identity $user -Properties displayName, givenName, name

        # 检查displayName和givenName字段是否以"2"结尾
        if ($adUser.displayName -match "2$") {
            $newDisplayName = $adUser.displayName -replace "2$", ""
            $adUser | Set-ADUser -DisplayName $newDisplayName -ErrorAction Stop
            Write-Host "已更新 $($adUser.sAMAccountName) 的 displayName 为 $newDisplayName"
        }

        if ($adUser.givenName -match "2$") {
            $newGivenName = $adUser.givenName -replace "2$", ""
            $adUser | Set-ADUser -GivenName $newGivenName -ErrorAction Stop
            Write-Host "已更新 $($adUser.sAMAccountName) 的 givenName 为 $newGivenName"
        }

        if ($adUser.name -match "2$") {
            $newname = $adUser.name -replace "2$", ""
            Rename-ADObject -Identity $adUser.DistinguishedName -NewName $newname
            Write-Host "已更新 $($adUser.sAMAccountName) 的 name 为 $newname"
        }
    }
    catch {
        Write-Host "处理域账号 $user 时出错: $_"
    }
}
Windows相关使用技巧工作学习小妙招

【Windows激活小技巧】如何恢复电脑出厂自带的正版激活状态?

2024-9-9 13:12:19

Windows相关使用技巧工作学习小妙招

Win10通用安装设置页面

2024-9-17 22:48:51

搜索