Tuesday, March 21, 2017

Upload AD Photos to Office 365

So, an interesting issue I came across the other day. My customer wanted to copy all photos from AD to Office 365. Since I hate doing manual labor, or leaving it to each user to re-upload their pictures, I came up with this simple script.

All you have to do is enter your Office 365 admin credentials into the script, and run it from a Domain Admin account within your environment.

# Set Credentials
$Username = "admin@tenant.onmicrosoft.com"
$Password = ConvertTo-SecureString 'MyPassword' -AsPlainText -Force
$UserCredential = New-Object System.Management.Automation.PSCredential $Username, $Password

#Connect to O365 Exchange Online
$ConnectionURI = "https://outlook.office365.com/powershell-liveid/?proxymethod=rps"
$EXSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri $ConnectionURI -Credential $UserCredential -Authentication Basic -AllowRedirection
Import-PSSession $EXSession -AllowClobber

#Get Mailboxes
$Mailboxes = (Get-MailBox -ResultSize Unlimited |?{$_.IsDirSynced -eq "True"})

foreach($Mailbox in $Mailboxes){
  $ADPhoto = $Null
  $ADPhoto = (Get-AdUser -Identity $Mailbox.Alias -Properties thumbnailPhoto).thumbnailPhoto
  If($ADPhoto.Length -ne 0){
    Write-Host -ForegroundColor Green "Uploading Picture for $($Mailbox.Name)"
    Set-UserPhoto -Identity $Mailbox.Alias -PictureData ([byte[]]$ADPhoto) -Confirm:$False
  }
}

Remove-PSSession $EXSession

Please let me know if you find a better way of doing this.

P.S. don't worry about the errors, as I have not put any error checking into this script.