SharePoint Online: Sync User Profile Property from Azure AD using PowerShell

Requirement: Sync User Profile Property from Azure Active Directory to SharePoint Online using PowerShell

How to Sync a User Profile Property in SharePoint Online?
In a typical SharePoint Online environment, The user profile synchronization process imports user profiles from On-Premises AD to Azure (through AD Sync Tool), and then from the Azure Active Directory (AAD) certain properties are mapped and synchronized with the SharePoint Online User Profiles. Not all the properties from Azure AD are synced to SharePoint Online. I've got a requirement to sync "Mobile Phone" Property to SharePoint Online user profile. Although the Azure AD Sync tool imports "Mobile" property from On-Premises AD, SharePoint doesn't have a mapping for this property!

And the bad news is: currently there are no ways to map and synchronize additional properties from the SharePoint Online Administration page (As we do in SharePoint On-Premises). However, we can loop through the users from Azure AD and update the User Profile Property in SharePoint Online using CSOM PowerShell script.
sharepoint online sync user profile property powershell

PowerShell to Import a User Profile Property in SharePoint Online:
Using the Azure AD PowerShell and the SharePoint Client Side Object Model (CSOM), we can get the user profile property value from Azure AD and update the corresponding properties in the SharePoint Online User Profiles and then schedule this script to run on a regular basis. Let's sync mobile phone from azure active directory to SharePoint Online using PowerShell.
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -Path "C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.UserProfiles.dll"

Function Sync-UserProfileProperty()
{
    Param
    (
        [Parameter(Mandatory=$true)] [string] $AdminSiteUrl,
        [Parameter(Mandatory=$true)] [string] $UserPrincipalName,
        [Parameter(Mandatory=$true)] [string] $ADPropertyName,
        [Parameter(Mandatory=$true)] [string] $SPOPropertyName
    )
    #Get Credentials to connect
    $Cred = Get-Credential
 
    Try {
        #Connect to AzureAD
        Connect-AzureAD -Credential $Cred | Out-Null
 
        #Get the User Property from AzureAD
        $AzureADUser = Get-AzureADUser -ObjectId $UserPrincipalName
        $ADUserPropertyValue = $AzureADUser | Select -ExpandProperty $ADPropertyName
        #To get extended property value, use: $AzureADUser.ExtensionProperty.Item($ADPropertyName)

        #Setup the context
        $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($AdminSiteUrl)
        $Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
  
        #Get User Profile Manager
        $PeopleManager = New-Object Microsoft.SharePoint.Client.UserProfiles.PeopleManager($Ctx)
  
        #Sync User Profile Property from AD
        $UserAccount = "i:0#.f|membership|$UserPrincipalName"
        $PeopleManager.SetSingleValueProfileProperty($UserAccount, $SPOPropertyName, $ADUserPropertyValue)
        $Ctx.ExecuteQuery()
        Write-host "User Profile Property has been Synched for: $UserPrincipalName" -f Green 
    }
    Catch {
        write-host -f Red "Error Synching User Profile Property!" $_.Exception.Message
    }
}
#Config parameters
$AdminSiteUrl = "https://crecent-admin.sharepoint.com"
$UserPrincipalName = "[email protected]"
$ADPropertyName = "MobilePhone"
$SPOPropertyName = "CellPhone"

#Call the function to sync a Property from Azure AD to SharePoint Online
Sync-UserProfileProperty -AdminSiteUrl $AdminSiteURL -UserPrincipalName $UserPrincipalName -ADPropertyName $ADPropertyName -SPOPropertyName $SPOPropertyName

This PowerShell script imports a given property from Azure AD to SharePoint Online for a particular user. Make sure you have Azure AD Module installed in your machine prior running this script:
Install-Module AzureAD

PowerShell to Sync User Profile Property Value for All Users
This time, let's sync a user profile property for all users from Azure AD to SharePoint Online using PnP PowerShell. In addition, let's check:
  1. If the AD user profile property has some value (not null!)
  2. If the user profile property in SharePoint Online doesn't have any existing value in it!
#Config Variables
$AdminSiteURL = "https://crescent-admin.sharepoint.com"
$ADPropertyName = "Department"
$SPOPropertyName = "Department"

#Get Credentials to connect to Azure AD and SharePoint Online Admin Center
$Cred = Get-Credential

Try {
    #Connect to AzureAD
    Connect-AzureAD -Credential $Cred | Out-Null

    #Get All Users of the Domain from AzureAD 
    $AllUsers = Get-AzureADUser -All:$True -Filter "UserType eq 'Member'" 
    Write-host "Total Number of User Profiles Found:"$AllUsers.Count  

    #Connect to PnP Online
    Connect-PnPOnline -Url $AdminSiteURL -Credentials $Cred

    #Iterate through All Users
    $Counter = 1
    ForEach($User in $AllUsers)
    {
        Write-host "`nUpdating User Profile Property for: $($User.UserPrincipalName)" -f Yellow

        #Get the User Property value from Azure AD        
        $ADUserPropertyValue = $User | Select -ExpandProperty $ADPropertyName

        #Check if the AD Property is not Null
        If (!([string]::IsNullOrEmpty($ADUserPropertyValue))) 
        {
            #Get existing User Profile Property from SharePoint
            $UserAccount = "i:0#.f|membership|$($User.UserPrincipalName)"
            $UserProfile = Get-PnPUserProfileProperty -Account $UserAccount
            $UserProfileProperty = $UserProfile.UserProfileProperties[$SPOPropertyName]

            #Check if the Existing SharePoint User Profile Property is Null
            If (([string]::IsNullOrEmpty($UserProfileProperty))) 
            {
                Set-PnPUserProfileProperty -Account $UserAccount -PropertyName $SPOPropertyName -Value $ADUserPropertyValue
                Write-host "`tUpdated User Profile Property for: $($User.UserPrincipalName)" -f Green
            }
            Else
            {
                Write-host "`t Existing Value of the Property in SharePoint is Not Null! Skipping..." -f Yellow
            }
        }
        else
        {
            Write-host "`t AD Value of the Property is Null! Skipping..." -f Yellow
        }
        $Counter++
        Write-Progress -Activity "Updating User Profile Data..." -Status "Updating User Profile $Counter of $($AllUsers.Count)" -PercentComplete (($Counter / $AllUsers.Count)  * 100)
    }
}
Catch {
    write-host -f Red "Error Updating User Profile Property!" $_.Exception.Message
}

Default user profile property mappings in SharePoint Online
Here is the list of user profile properties mapped and synched to SharePoint Online from Azure AD.
SharePoint Online User profile property Azure Active Directory attribute
AccountName msonline-UserPrincipalName
ADGuid ObjectGuid
Department Department
FirstName GivenName
GroupType GroupType
IsPublic msOnline-IsPublic
IsUnifiedGroup msonline-groupType
LastName sn
Manager Manager
msOnline-ObjectId msOnline-ObjectId
msOnline-ObjectId msOnline-ObjectId
Office PhysicalDeliveryOfficeName
PreferredName DisplayName
PublicSiteRedirect WWWHomePage
SPO-IsSPO SPO-IsSharePointOnlineObject
SPS-ClaimID msonline-UserPrincipalName
SPS-Department Department
SPS-DistinguishedName DistinguishedName
SPS-HideFromAddressLists msExchHideFromAddressList
SPS-JobTitle Title
SPS-MUILanguages PreferredLanguage
SPS-RecipientTypeDetails msExchRecipientTypeDetails
SPS-SavedSID ObjectSid
SPS-SIPAddress proxyAddresses
SPS-UserPrincipalName msonline-UserPrincipalName
SPS-UserType msOnline-UserType
Title Title
UserName msonline-UserPrincipalName
WorkEmail proxyAddresses
WorkPhone telephoneNumber

Please note, This property update is only for SharePoint Online, it can't be synced to Office 365 or Azure AD. User profile property created in the SharePoint Online admin center will not create or sync that property in Office 365! We also have a API to bulk update user profile properties Bulk update custom user profile properties for SharePoint Online

5 comments:

  1. Hi, Does it work for a custom property in On-Premise AD which is synced to Azure AD ?
    In another words, If we create a custom user profile property in User profile application within SPO, with the above script can we sync any corresponding custom attribute from Local Ad to Azure AD to the Custom User Profile property?

    ReplyDelete
  2. Hi,
    Can a custom property in On-Premise AD be synced to Azure AD and then synced to a Custom User profile property in SPO, using this approach? Or does it only work for standard properties of AD?

    ReplyDelete
    Replies
    1. Yes! It works for any Azure AD Properties, Including Custom user profile properties from AD!

      Delete
  3. Can I use this script to sync "Country or Region" from Azure AD to SharePoint user profile property? Just change these values?
    $ADPropertyName = "Country"
    $SPOPropertyName = "Country"

    second question. I assumed I have to create a custom managed property in SharePoint called "Country"?

    ReplyDelete
    Replies
    1. Yes, You can create a custom user profile property and then use above script to sync it from Azure AD. How to create user profile property in SharePoint Online?

      Delete

Please Login and comment to get your questions answered!

Powered by Blogger.