Microsoft Graph API – Powershell, Download user Images

Read Time:2 Minute, 2 Second

In my previous post, we went over how to Grab user information from a client. Today we will be going over how to get the photo. This piece is very straightforward until you get to the graph link. There is a unique limitation to PowerShell quotes that I found a good workaround.

Ok, we start off with the loop like before. We are using the /Users API. Since this is a user-level item, you have a top loop through each user with the User Principal Name. This means your string will be inside double quotes “” instead of single quotes because you want PowerShell to read the value of the $($UPN). so far simple. The next part is the word photo. Once again, simple. Then the impact. the word $value has to be at the end. This means it’s going to drop whatever is instead value into the string. There are a few ways around this.

Option 1

Declare the variable beforehand. Simple and easy way to fix this problem.

$Value = '$value'
$UserPhotoLink = "$($UPN)/photo/$value"

Options 2

Use the + symbol to add the string.

$UserPhotoLink = "$($UPN)/photo/" + '$value'

Downloading the Image

Now we have the link we need to download the image. Once again we are going to use the invoke-restmethod with our custom header like before. This time we are going to give the -outfile. Since not everyone has an image, I am also going to set the error action to silently continue.

Invoke-RestMethod -Method get -Headers $Header -Uri $UserPhotoLink -ErrorAction SilentlyContinue -OutFile "$DropPath\$($UPN).jpg" 

That’s it. The for loop will allow you to download all of your user’s images with the UPN as the file name. I hope this has been helpful.

You Might Also Like

Leave a Reply

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.