How to Use Get-MgUserPhoto in Microsoft Graph PowerShell: Examples and Tips

The Get-MgUserPhoto cmdlet is a powerful tool for retrieving the profile photos of users in Microsoft 365. This cmdlet can be used to manage or display user photos in applications or reports. In this article, we'll explore various usage examples, including how to get user photo URLs and retrieve user photos from a user list in a CSV file.


Prerequisites

  • Install the Microsoft Graph PowerShell module by running Install-Module Microsoft.Graph -Scope CurrentUser.
  • Ensure you have the necessary permissions to read user data. Connect to Microsoft Graph with the following command: Connect-MgGraph -Scopes "User.Read.All"

Basic Usage


Retrieve Photo by User Principal Name (Email)

Get-MgUserPhoto -UserId "user@domain.com"

Retrieve Photo by User ID

Get-MgUserPhoto -UserId "user-id"

Advanced Usage Scenarios


Retrieve User Photo URL

To get the URL of a user's photo, you need to format the URL correctly using the user's ID or principal name. Here's an example of how to construct the URL:

$userId = "user@domain.com"
$photoUrl = "https://graph.microsoft.com/v1.0/users/$userId/photo/$value"
Write-Host "User photo URL: $photoUrl"

Retrieve User Photos from User List in a CSV File

You can retrieve user photos for multiple users listed in a CSV file. The CSV file should have a column for user IDs or emails.

Example CSV File (users.csv):

UserId
user1@domain.com
user2@domain.com
user3@domain.com

PowerShell Script to Retrieve Photos from CSV

# Import the CSV file
$users = Import-Csv -Path "C:\path\to\your\users.csv"

# Loop through each user and retrieve their photo
foreach ($user in $users) {
    $userId = $user.UserId
    try {
        $photo = Get-MgUserPhoto -UserId $userId
        $photoBytes = [System.Convert]::FromBase64String($photo.ContentBytes)
        $filePath = "C:\path\to\photos\$($userId).jpg"
        [System.IO.File]::WriteAllBytes($filePath, $photoBytes)
        Write-Host "Photo saved for user: $userId"
    } catch {
        Write-Host "Error retrieving photo for user: $userId"
    }
}

Cmdlet Usage Tips

  • Ensure Proper Permissions: Make sure the account running the cmdlet has the necessary permissions to read user photos.
  • Use Variables for Reusability: Store frequently used values in variables for easier reuse and readability.
  • Handle Exceptions Gracefully: Use try-catch blocks to handle errors and ensure your script continues running even if it encounters an issue with a specific user.

Frequently Asked Questions

  • Can I retrieve different sizes of user photos with Get-MgUserPhoto?
  • Yes. Microsoft Graph supports multiple sizes (small, medium, large, and custom dimensions). You can request a specific size using the -Size parameter in the API call, though in PowerShell you’ll typically retrieve the default photo.

  • What happens if a user does not have a photo set?
  • If no photo exists, the command will return an error or an empty result. In such cases, you may want to implement error handling or set a default placeholder image in your scripts.

  • Can I update or set user photos with Graph PowerShell?
  • Yes. While Get-MgUserPhoto is for retrieval, you can use Set-MgUserPhotoContent to upload or replace a user’s profile picture. This requires proper permissions and admin rights.

  • What permissions are required to fetch user photos?
  • You need User.Read, User.ReadBasic.All, or User.Read.All delegated permissions for standard use. For application-level access, ensure your app is granted the equivalent permissions in Azure AD.


Possible Errors and How to Overcome Them

Error Cause Solution
Access Denied Insufficient permissions to access user photos. Ensure you have the necessary permissions. You may need to grant the appropriate permissions in the Azure portal.
Invalid UserId The provided UserId does not correspond to an existing user. Verify the UserId is correct and corresponds to an existing user in your directory.
User Photo Not Found The user does not have a profile photo set. Check if the user has uploaded a profile photo. If not, consider handling this scenario in your script, possibly by displaying a default photo.
try {
$photo = Get-MgUserPhoto -UserId "user@domain.com"
# Process photo
} catch {
Write-Host "User photo not found. Using default photo."
# Use default photo logic
}
                                    

💡 Cache Photos Locally to Reduce API Load

When operating in scripts that run often, download and cache profile photos locally (or in a shared store). Before fetching, check the cache; if the photo already exists, skip the Graph API call. This reduces repetitive calls, saves bandwidth, and avoids throttling.
💡 Respect Image Size and Format Limitations

Graph returns user photos in specific sizes (like small, medium, large) and formats (JPEG/PNG). When saving photos, ensure your script handles potential format mismatches (e.g., converting PNG to JPG) and respects maximum sizes to avoid corrupted images or errors.

Conclusion

The Get-MgUserPhoto cmdlet is versatile and can be tailored to your needs by using various parameters and techniques. By utilizing the cmdlet in combination with PowerShell scripting, you can efficiently retrieve and manage user photos in Microsoft 365.

For more detailed information, you can refer to the official Microsoft documentation.


Related Articles:

Using Get-MgDirectoryRole in Graph PowerShell
Using Get-MgUserLicenseDetail in Graph PowerShell
Using Find-GraphMgCommand in Graph PowerShell
Connect to Microsoft 365 Using PowerShell
How to Create Bulk Users in Office 365 Using Graph PowerShell?
Create Microsoft 365 Group Using Microsoft Graph PowerShell
Block Microsoft 365 User Using Microsoft Graph PowerShell
Assign Microsoft 365 License Using Graph PowerShell
Microsoft 365 User Management Using Graph PowerShell
Checking Group Membership in Microsoft 365
Bulk Assign Microsoft 365 License
Find Inactive Users in Microsoft 365
Using Powershell Graph Search Query
Using Powershell Graph Filter Query
Using Where-Object In Graph PowerShell
Using Expand Property In Graph PowerShell
Using Select Object In Graph PowerShell
Using -Contains Operator In Graph PowerShell
Add User to Multiple Microsoft 365 Groups Using Graph PowerShell
Get Microsoft 365 User Location Using Graph PowerShell
Import Microsoft 365 Groups from CSV File Using Graph PowerShell
Microsoft 365 Group User Import Using Graph PowerShell

© m365corner.com. All Rights Reserved. Design by HTML Codex