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
CodePudding user response:
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
}