Trying to add new property on each user of a variable

Welcome Forums General PowerShell Q&A Trying to add new property on each user of a variable

This topic contains 3 replies, has 2 voices, and was last updated by

3 years, 5 months ago.

  • Author
  • #27640

    Points: 42
    Rank: Member


    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)...

  • #27644

    Points: 42
    Rank: Member

    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?

  • #27646

    Points: 324
    Helping Hand
    Rank: Contributor

    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,
  • #27734

    Points: 42
    Rank: Member

    Rob Simmers,


The topic ‘Trying to add new property on each user of a variable’ is closed to new replies.