Trying to add new property on each user of a variable


I’m trying to update Active Directory users information using Office 365 information.
The first step was to retrieve all users I have on Office 365:

$Users = Get-msoluser | sort UserPrincipalName

Then I need to add a property called ADUser on each one (because my Active Directory isn’t federated with Office 365, then… AD user is different that Office 365 user.)
I’ve tried something like this:

$ADUsers = @() $ADUsers = foreach ($User in $Users){$User | Add-Member NoteProperty ADUser (Get-ADUser -Filter * -Properties mail,SamAccountName | where {$_.mail -eq $User.UserPrincipalName}).SamAccountName}

Obviously it isn’t working… But I don’t know a way to do it.
All I need is to add that property on every user and put them on another variable (or the same if this can be done)…

Nevermind… Been able to do the task with this command:

$Users | ForEach-Object {$_ | Add-Member NoteProperty ADUser (Get-ADUser -Filter {mail -eq $_.UserPrincipalName} -Properties SamAccountName).SamAccountName}

PS: How can I check this post as resolved?

Your logic isn’t quite correct. You are returning ALL AD users and then filtering to find a user, for every person in your Get-MSOLUser dump, which is going to take a long time. Take a look at this logic that searches for the AD User, gets the SamAccountName and then we return the UPN from $users (Get-MSOLUser) and add a property for SamAccountName from $AdUser (Get-ADUser):

$ADUsers = foreach ($User in $Users){
    $ADUser  = Get-ADUser -Filter "Mail -eq $User.UserPrincipalName" -Properties mail,SamAccountName
    $User | Select UserPrincipalName,

Rob Simmers,