Listen to this Post
This article explores a PowerShell script designed to automate Entra ID (formerly Azure AD) user photo updates using Microsoft Graph API. The script efficiently manages user photos without requiring the Microsoft.Graph module, leveraging `Invoke-RestMethod` for direct API calls.
Key Features
- Uses a Managed Identity for authentication.
- Runs on an Azure Arc-enabled server via a Hybrid Worker.
- Minimizes unnecessary API calls to reduce consumption.
- Matches users with local photos and updates profiles seamlessly.
You Should Know: Practical Implementation
1. Authentication with Managed Identity
Ensure your Hybrid Worker has the necessary permissions to access Microsoft Graph. Use the following PowerShell snippet to authenticate:
$resource = "https://graph.microsoft.com" $token = (Get-AzAccessToken -ResourceUrl $resource).Token $headers = @{ "Authorization" = "Bearer $token" "Content-Type" = "application/json" }
2. Fetching Users from Entra ID
Retrieve all users and store them in an ordered hash table for efficient processing:
$uri = "https://graph.microsoft.com/v1.0/users" $users = Invoke-RestMethod -Uri $uri -Headers $headers -Method Get $userTable = @{} $users.value | ForEach-Object { $userTable[$<em>.id] = $</em> }
3. Updating User Photos
To update a user’s photo, use a direct Graph API call:
$userId = "USER_ID" $photoPath = "C:\photos\$userId.jpg" $photoBytes = [System.IO.File]::ReadAllBytes($photoPath) $photoBase64 = [System.Convert]::ToBase64String($photoBytes) $uri = "https://graph.microsoft.com/v1.0/users/$userId/photo/`$value" Invoke-RestMethod -Uri $uri -Headers $headers -Method Put -Body $photoBase64
4. Optimizing API Calls
To avoid excessive API consumption, implement checks before updating:
$currentPhoto = Invoke-RestMethod -Uri "https://graph.microsoft.com/v1.0/users/$userId/photo" -Headers $headers -Method Get if (-not $currentPhoto) { <h1>Update photo only if none exists</h1> }
What Undercode Say
Automating Entra ID user photos is just the beginning—this approach can extend to broader Microsoft 365 management. Key takeaways:
– Use Managed Identities for secure authentication.
– Leverage Hybrid Workers for on-premises/Azure hybrid automation.
– Optimize API calls to minimize costs.
– Explore Graph API beyond photos (e.g., user provisioning, group management).
For further reading, check the original post: GitHub – AllwaysHyPe/graph-automation.
Expected Output:
A fully automated script that updates Entra ID user photos efficiently while minimizing API overhead.
References:
Reported By: Hailey Phillips – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅