# Import modules Import-Module -Name MSAL.PS Import-Module -Name ExchangeOnlineManagement Import-Module -Name AzureADPreview Import-Module -Name Microsoft.Graph.PersonalContacts Import-Module -Name Microsoft.Graph.Authentication Import-Module -Name Microsoft.Graph.Applications # Variables $thumbprint = XXXXXX $appId = XXXXXX $tenant = XXXXXXXX $serviceId = XXXXXXXXX $appSecret = XXXXXXXX $tenantId = XXXXXXXXXX $dlOrgContactId = XXXXXXXXXXXXXXXXXXXXXXX $folderName = XXXXXXXXXXXXXXXXXXXX $folderId = XXXXXXXXXXXXXXX $Now = Get-Date -format D $OrgNotes = "Organization contact created " + $Now # Oauth connection to EXO try { Connect-ExchangeOnline -CertificateThumbprint $thumbprint -AppId $appId -Organization $tenant write-host -ForegroundColor Green "Connection Successfull to EXO" } catch { write-host -ForegroundColor Red "Connection Error to EXO" } # Oauth connection to AAD try { Connect-AzureAD -TenantId $tenantId -CertificateThumbprint $thumbprint -ApplicationId $appId write-host -ForegroundColor Green "Connection Successfull to AAD" } catch { write-host -ForegroundColor Red "Connection Error to AAD" } # Find the set of organization contacts from DL All Staff Contact [array]$OrgContacts = [array]$OrgContacts = Get-AzureADGroupMember -ObjectId $dlOrgContactId -All:$true If (!($OrgContacts)) {Write-Host "No organization contacts found - exiting" ; break } Write-Host ("Found {0} organization contacts - continuing..." -f $OrgContacts.count) # Look for target mailboxes. In this example, we get the mailboxes created in the last month $LastMonth = (Get-Date).AddDays(-30) [array]$Mailboxes = Get-ExoMailbox -Filter "WhenMailboxCreated -gt '$LastMonth'" -RecipientTypeDetails UserMailbox | Select ExternalDirectoryObjectId, DisplayName, UserPrincipalName If (!($Mailboxes)) { Write-Host "No mailboxes found to process - exiting" ; break } Write-Host ("Found {0} mailboxes to process - continuing..." -f $Mailboxes.count) # Grant Full Access to Org Contacts Mailboxes ForEach ($m in $OrgContacts) { # Grant Full Acces to Mailbox Add-MailboxPermission -Identity $m.Mail -User $serviceId -AccessRights FullAccess -InheritanceType All } # Get Token for Graph Api $MsalResponse = Get-MsalToken -ClientId $appId -TenantId $tenant -ClientSecret (ConvertTo-SecureString $appSecret -AsPlainText -Force) -Scopes "https://graph.microsoft.com/.default" -ForceRefresh $GraphToken = $MsalResponse.AccessToken # Connect Graph API Connect-MgGraph -AccessToken $GraphToken ForEach ($Mbx in $Mailboxes) { # Populate email addresses for existing contacts $folderStaffDirectory = Get-MgUserContactFolder -UserId $Mbx.UserPrincipalName | Where-Object {$_.DisplayName -eq $folderName} # Create contacts folder if does not exists if(!($folderStaffDirectory)) { $paramsFolder = @{ ParentFolderId = $folderId DisplayName = $folderName } # Create folder $folderStaffDirectory = New-MgUserContactFolder -UserId $Mbx.UserPrincipalName -BodyParameter $paramsFolder } # Get contacts from folder [array]$ContactsInMbx = Get-MgUserContactFolderContact -UserId $Mbx.UserPrincipalName -ContactFolderId $folderStaffDirectory.Id -All If ($ContactsInMbx.Count -gt 0) { $ContactsInMbx = $ContactsInMbx | Select emailaddresses } $CheckTable = [System.Collections.Generic.List[Object]]::new() ForEach ($C in $ContactsInMbx) { $CheckTable.Add($C[0].EmailAddresses[0].Address.toString()) } Write-Host "Processing mailbox" $Mbx.DisplayName ForEach ($Contact in $OrgContacts) { Write-Host "Processing contact" $Contact.DisplayName # Check if the contact is already there. If not, we go ahead and add the contact If ($Email -in $CheckTable) { Write-Host ("Contact record for {0} is already present in the mailbox" -f $Contact.Maill) } Else { Write-Host "Proceeding $($Contact.Mail)..." # Build the contact object $params = @{ GivenName = "$($Contact.GivenName)" Surname = "$($Contact.Surname)" EmailAddresses = @( @{ Address = "$($Contact.Mail)" Name = "$($Contact.DisplayName)" } ) BusinessPhones = @( "$($Contact.TelephoneNumber)" ) } # And add the new contact Try { New-MgUserContactFolderContact -UserId $Mbx.UserPrincipalName -BodyParameter $params -ContactFolderId $folderStaffDirectory.Id -DisplayName $Contact.DisplayName -CompanyName $Contact.CompanyName -Department $Contact.Department -JobTitle $Contact.JobTitle -PersonalNotes $OrgNotes -MobilePhone $Contact.Mobile } catch { Write-Host "Error creating contact $($Contact.Mail) for $($Mbx.UserPrincipalName) $($_.Exception.Message)" } } #End Else } #End ForEach OrgContacts } #End ForEach Mailboxes