简体   繁体   中英

Error while Renaming AD user using powershell

I am having the below code which I am using for Renaming the cn of the user

$path = "OU=Accounts,OU=IT,OU=$dcs1,DC=z,DC=if,DC=ag,DC=net" 


$ExportPath=@()
$Result=@()

$ExportPath = Get-ADUser -Filter "Name -like 'clean1_*'" -SearchBase $path | select -First 1

foreach($Usr in $ExportPath)
{

    Rename-ADObject -Identity $Usr -NewName {$Usr.Name -replace '^clean1_'} 
 
}

it is executing the making changes in AD like below. Original Name was clean1_Reena_K (W00-198)

在此处输入图像描述

Please let me know on this

I hope you are replace clean1_Reena_K (W00-198) value into Reena_K .

Follow the Work around to fix:

Way 1:

For that you have to use the Regex to find and replace .

# syntax 
# String -replace -replace  ([regex]::Escape('<Text to find in string >')),'<Replace text>'

'$Usr.Name' -replace  ([regex]::Escape('clean1_')),'' 

Way 2

In an Identity you have to keep the DistinguishedName . As per I have slightly changed your code

$path = "OU=Accounts,OU=IT,OU=$dcs1,DC=z,DC=if,DC=ag,DC=net" 
$ExportPath=@()
$Result=@()

$ExportPath = Get-ADUser -Filter "Name -like 'clean1_*'" -SearchBase $path | select -First 1

foreach($Usr in $ExportPath)
{
     $DistName = $Usr.DistinguishedName
     $CName = $Usr.Name
     $newName = ([String]$CName).Replace("^clean1_","")
    
     Rename-ADObject -Identity $DistName -NewName $newName
 
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM