This morning some awesome people helped me make a script to move user accounts based on their displayName to a certain OU. I tested and it worked. I cannibalized the script to make another one that will rename the same accounts based off of the same criteria. I've gone through several errors but basically it all boils down to "I am having an identity crisis!". I can't seem to figure out exactly what I need to input as the $Identity
. Here is what I have:
Import-Module ActiveDirectory
$Renames = @(
@{
Filter = 'DisplayName -like "*Supply*"'
NewName = "Supplies"
},
@{
Filter = 'DisplayName -like "*Accountant*"'
NewName = "Accounting"
}
) | ForEach-Object {New-Object -TypeName PSCustomObject -Property $_}
$OriginOU = "OU=Test,OU=Standard Users,OU=Domain Users,DC=com"
foreach ($Rename in $Renames) {
Get-ADUser -SearchBase $OriginOU -Filter $Rename.Filter -Properties displayName |
Where-Object {($_.Enabled -eq 'True') -and ($_.DistinguishedName -notlike '*DontTouch*')} |
%{Set-ADUser $_ -DisplayName {$_.DisplayName -replace '(.EPSILON ).+',"`$1$Rename.NewName"}}
}
You can't use the current object variable (
$_
) if you haveSet-ADUser
read directly from the pipeline. And sinceSet-ADUser
apparently doesn't play nice with scriptblock arguments, you have to put the statement in a loop:Note that if you want to expand object properties inside a string you have to put
$Rename.NewName
in a subexpression ($()
), otherwise the whole object$Rename
would be stringified and the string ".NewName" would be appended to it.