Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
### Azure AD / M365 profile picture uploader
### Version 1.0
### Author: Alexander Holmeset
### Email:
### Twitter:
### Blog:
$TenantId = "xxxxxxx"
$ClientID = "xxxxxx"
$ClientSecret = "xxxxx"
#Folder where you have the profilepictures.
$filefolder = "c:\temp\"
function Get-MSGraphAppToken{
Get an app based authentication token required for interacting with Microsoft Graph API
A tenant ID should be provided.
Application ID for an Azure AD application. Uses by default the Microsoft Intune PowerShell application ID.
.PARAMETER ClientSecret
Web application client secret.
# Manually specify username and password to acquire an authentication token:
Get-MSGraphAppToken -TenantID $TenantID -ClientID $ClientID -ClientSecert = $ClientSecret
Author: Jan Ketil Skanke
Contact: @JankeSkanke
Created: 2020-15-03
Updated: 2020-15-03
Version history:
1.0.0 - (2020-03-15) Function created
param (
[parameter(Mandatory = $true, HelpMessage = "Your Azure AD Directory ID should be provided")]
[parameter(Mandatory = $true, HelpMessage = "Application ID for an Azure AD application")]
[parameter(Mandatory = $true, HelpMessage = "Azure AD Application Client Secret.")]
Process {
$ErrorActionPreference = "Stop"
# Construct URI
$uri = "$tenantId/oauth2/v2.0/token"
# Construct Body
$body = @{
client_id = $clientId
scope = ""
client_secret = $clientSecret
grant_type = "client_credentials"
try {
$MyTokenRequest = Invoke-WebRequest -Method Post -Uri $uri -ContentType "application/x-www-form-urlencoded" -Body $body -UseBasicParsing
$global:MyToken =($MyTokenRequest.Content | ConvertFrom-Json).access_token
Write-Warning "Failed to get Graph API access token!"
Exit 1
$MyHeader = @{"Authorization" = "Bearer $global:MyToken "}
catch [System.Exception] {
Write-Warning "Failed to get Access Token, Error message: $($_.Exception.Message)"; break
return $MyHeader
#Generates Graph API token.
$Header = Get-MSGraphAppToken -TenantID $TenantId -ClientID $ClientID -ClientSecret $ClientSecret
$Header = @{"Authorization" = "Bearer $global:MyToken" ;'Content-Range' = "bytes 0-$($fileLength-1)/$fileLength";"content-type" = "image/jpeg"}
#Load profile pictures from folder.
$files = get-childitem -path $filefolder | select-object Extension,name
foreach($file in $files){
#Path of the current file
$path = $filefolder+$($
#Convert profile picture to bytes.
$fileInBytes = [System.IO.File]::ReadAllBytes($path)
$fileLength = $fileInBytes.Length
$upn = @()
$upn = ($$($file.Extension)),"")
$URI = "$upn/photo/`$value/"
$response = Invoke-RestMethod -Method 'Put' -Uri $URI -Body $fileInBytes -Headers $Header
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment