In my previous post, we went over how to Grab user information from a client. Today we will be going over how to Download User Images with Graph API. 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'

Download User Images with Graph API

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.

More Information: