Set-ADUser multiple Identities not working

Hello all, wanted to see about a hand on this script. I am trying to pass a couple variables into AD user attribute. It works when targeting one user, but when I add multiple it fails, or adds all values for each user. Not sure what I am missing, or if there is a better way to do this…thanks

#Establishing Search Base OU
$Base = "OU=TST,OU=IT,DC=domain,DC=com

#Query and Set Values Replacement Attributes
$GivenName = (Get-ADUser -SearchBase $Base -Filter { (idautoPersonPreferredName -notlike "*") -and (idautoPersonPreferredLastName -notlike "*") -and (enabled -eq $true) } -Properties GivenName).GivenName; 
$SurName = (Get-ADUser -SearchBase $Base -Filter { (idautoPersonPreferredName -notlike "*") -and (idautoPersonPreferredLastName -notlike "*") -and (enabled -eq $true) } -Properties Surname).Surname;
$User = (Get-ADUser -SearchBase $Base -Filter { (idautoPersonPreferredName -notlike "*") -and (idautoPersonPreferredLastName -notlike "*") -and (enabled -eq $true) } -Properties "Name").Name;

#Set User Attributes
ForEach-Object {
Set-ADUser -Identity "$User" -Replace @{ idautoPersonPreferredName="$GivenName";idautoPersonPreferredLastName="$SurName" }
}

Foreach-Object requires a pipe in front of it to work the way you probably expect it to. I’d recommend to (re-)read the help completely including the examples to learn how to use it. :wink: There are a lot of examples for such a task either here or in the PowershellGallery or in StackOverflow. It’s not a bad habbit to learn from others having been there where you want to go.

Another possible option would be to use the foreach loop instead of Foreach-Object.

Hello Olaf,

Thanks for the info on that! I found another way around it to get it to run properly. But will definitely give that a go…

You may share your solution to help others having the same or a similar problem and looking for a solution. That’s how a forum works. :wink: