Sync Azure Active Directory Properties With Office 365 User Profile Using PowerShell

Introduction

 
In this article, we will see how can we sync properties of Azure Active Directory with Office 365 user profiles.
 
Pre-requisites 
  • Username and password of the user, who has exchange admin access.
  • Properties must be synced with any extension attribute in AAD (Azure Active Directory). Here in this article, we will show examples to sync the hire date and birth date of the user.
  • In this article's example, Birthdate is synced with extensionAttribute1, and hire date is synced with extensionAttribute2.
  • Requires the below DLL files,
    • Microsoft.SharePoint.Client.dll
    • Microsoft.SharePoint.Client.Runtime.dll
    • Microsoft.SharePoint.Client.UserProfiles.dll

  • All these DLL files must be available on the same folder where our PowerShell script file(.ps1) is saved.

Write Script

 
Now we will write a script to sync AAD properties with office 365 user profiles,
 
Step 1
 
Declare a variable and assign the path of the current directory where the PowerShell script is saved.
  1. $CurrentDirPath = Split-Path $script:MyInvocation.MyCommand.Path     
Step 2
 
Now we will register Microsoft.SharePoint.PowerShell to Windows PowerShell snap-ins to the current session as shown below,
  1. Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue      
Step 3
 
Now we will load the DLL assemblies,
  1. [System.Reflection.Assembly]::LoadFrom("$CurrentDirPath\Microsoft.SharePoint.Client.dll")  
  2. [System.Reflection.Assembly]::LoadFrom("$CurrentDirPath\Microsoft.SharePoint.Client.Runtime.dll")  
  3. [System.Reflection.Assembly]::LoadFrom("$CurrentDirPath\Microsoft.SharePoint.Client.UserProfiles.dll")   
Step 4
 
Now define the path for the error file as below. It will create an errorInfo.txt file at the location where the script is saved.
  1. $FilePath = "$CurrentDirPath\erroInfo.txt";  
Step 5
 
Now define the site URL of the SharePoint administrator page in a variable.
  1. $SiteUrl = https://tenantname-admin.sharepoint.com/  
Step 6
 
Define the username and password as below,
  1. $sUserName = "sanjay@*****.onmicrosoft.com" 
  2. $sPassword = "**********"  
  3. $sPassword = ConvertTo-SecureString -String $sPassword -AsPlainText -Force   
Step 7
 
Define the credentials object as below,
  1. $credential = New-Object System.Management.Automation.PsCredential($sUserName,$sPassword)   
Step 8
 
Now we will connect to Azure AD using the Connect-AzureAD command as below,
  1. Connect-AzureAD -Credential $credential   
Step 9
 
Now connect to Exchange Online using the below command,
  1. Import-PSSession $exchangeSession  
Step 10
 
Now we will get all the users who have custom attribute 1 is not blank or custom attribute 2 is not blank and store all users in a variable.
 
Custom attribute 1 is for Birth date and Custom attribute 2 is for hire date.
  1. $users = Get-Mailbox -ResultSize unlimited -Filter { CustomAttribute1 -ne $null -or CustomAttribute2 -ne $null -or CustomAttribute3 -ne $null }  
Step 11
 
Now Create SharePoint Client Context of SharePoint Online Central Admin Site.
  1. $spoCtx = New-Object Microsoft.SharePoint.Client.ClientContext($sSiteUrl)    
  2. $spoCredentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($sUserName, $sPassword)    
  3. $spoCtx.Credentials = $spoCredentials      
Step 12
 
Initialize a new instance of PeopleManager Object.
  1. $peopleManager = New-Object   
  2. Microsoft.SharePoint.Client.UserProfiles.PeopleManager($spoCtx)    
Step 13
 
Now, we need to loop through all the users to update the hire date and birth date using below code,
  1. $users | ForEach-Object {     
  2. }   
Step 14
 
In a loop, write code to get the user principal name, custom attribute 1 and custom attribute 2. 
  1. $userName = $_.UserPrincipalName    
  2. $birthDay = $_.CustomAttribute1    
  3. $hireDate = $_.CustomAttribute2     
Here we assume, the birth date will In dd-MM format, and the hire date in MM/dd/yyyy format in AAD.
Step 15
 
Now we will update the birth date and hire date In the office 365 user profile as below,
  1. $UserProfilePrefix = "i:0#.f|membership|"
  2. If ($birthday -ne $null -and $birthday -ne "") {  
  3.         Try {  
  4.             # Format the birthday correctly              
  5.                           
  6.             $changeFormat = [datetime]::ParseExact($birthDay, "dd-MMM", $null);  
  7.             $birthdDate = "{0:MMM dd}" -f [datetime]$changeFormat                     
  8.  
  9.             # Update the property  
  10.             $peopleManager.SetSingleValueProfileProperty($UserProfilePrefix + $userName, "SPS-Birthday", $birthdDate)  
  11.             Write-Host "$userName has valid birthday in CustomAttribute1: $birthDay $birthdDate" -ForegroundColor Green  
  12.              
  13.             # Execute our changes  
  14.             $spoCtx.ExecuteQuery()  
  15.         }  
  16.         Catch {  
  17.          Write-Host “$userName does not have a valid birthday in CustomAttribute1: $birthDay $birthdDate” -ForegroundColor Red  
  18.          "------------------------------------------------------------"| Out-File $FilePath -Append  
  19.          "DATETIME = " + $(get-date) | Out-File $FilePath -Append  
  20.          "ERROR MESSAGE = " + $($_.Exception.Message) | Out-File $FilePath -Append   
  21.          "------------------------------------------------------------"| Out-File $FilePath -Append  
  22.         }  
  23.     }  
  24.      
  25.     # Update HireDate field  
  26.     If ($hireDate -ne $null -and $hireDate -ne “”) {  
  27.         Try {  
  28.             # Format the HireDate correctly              
  29.             $spshireDate = [datetime]::ParseExact($hireDate, "MM/dd/yy", $null);  
  30.  
  31.             # Update the property  
  32.             $peopleManager.SetSingleValueProfileProperty($UserProfilePrefix + $userName, "SPS-HireDate", $spshireDate)  
  33.             Write-Host "$userName has a valid HireDate in CustomAttribute2: $hireDate $spshireDate" -ForegroundColor Green  
  34.              
  35.             # Execute our changes  
  36.             $spoCtx.ExecuteQuery()  
  37.           
  38.         }  
  39.         Catch {  
  40.          Write-Host "$userName does not have a valid HireDate in CustomAttribute2: $hireDate $spshireDate" -ForegroundColor Red  
  41.          "------------------------------------------------------------"| Out-File $FilePath -Append  
  42.          "DATETIME = " + $(get-date) | Out-File $FilePath -Append  
  43.          "ERROR MESSAGE = " + $($_.Exception.Message) | Out-File $FilePath -Append   
  44.          "------------------------------------------------------------"| Out-File $FilePath -Append  
  45.         }  
  46.     }   
Step 16
 
At the end of script, dispose the SharePoint online context and remove connection to exchange online,
  1. $spoCtx.Dispose()  
  2. Remove-PSSession $exchangeSession   

Conclusion

 
This is how we can sync AAD properties with Office 365 user profile. Hope this article will be helpful!