Get-MgUserPhotoContent returns zero-length file

I have a PowerShell script that, for every user in our domain, pulls the photo down to the file system. For the vast majority it works fines. For some users, it returns a zero-length file despite them having a valid profile photon.

To handle this, I check the file length and if zero, sleep a little and try again. It sometimes takes 5 to 10 attempts to get a non-zero-length file. Although I can get through them all, this unnecessary sleeping makes the script run very long.

Below is the line of code that calls Get-MgUserPhotoContent. Any help would be appreciated.

Get-MgUserPhotoContent -UserId $userId -OutFile "$PhotoFilePath" -ErrorAction SilentlyContinue -ErrorVariable Err

Hello and welcome to the forum.
Please remember when you’re posting any kind of code to use the Preformatted Text option to properly format your code:
Guide to Posting Code

Just for clarification, you’re running the line as you shared correct? Suppressing errors? Are there any errors that occur when the output file results in a 0-byte file?
I see running a loop against all my team members that while it successfully downloads the photo for each one (over multiple attempts) it generates an error each time

Get-MgUserPhotoContent_Get:
Line |
   3 |  Get-MgUserPhotoContent -UserId $user -OutFile $file
     |  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Cannot set percent because PercentComplete cannot be greater than 100. (Parameter 'value')
Actual value was 2147483647.

Regardless this doesn’t seem to create an issue.

Can you share some more details about when this fails on your end?

The only errors I get when receiving a zero-length file are:

Cannot set percent because PercentComplete cannot be greater than 100. (Parameter ‘value’) Actual value was 2147483647.

That happens with all successful photo calls, hence the “SilentlyContinue” option.

Alright I tried to play along a little more on my own. Made an array of about 3600 users and looped through them to pull their picture down. Ended up with approximately 1800 photos. My loop had a Start-Sleep -Milliseconds 300 in it so this ended up taking over 35minutes.
Despite that there were 5 photos that were saved as 0-byte files, and upon retrying those users each one successfully downloaded a picture.

I suspect that this is some kind of rate limiting behavior on Microsoft’s end that we’re not going to get around.

Thanks for your reply and for testing this and confirming my experience. I have a while loop that attempts up to 10 tens sleeping 15 seconds in between. So far, it hasn’t gone beyond 10 attempts.

I thought about rate limit issues, but from what I read you should get the following error when that occurs: HTTP 429 “Too Many Requests” error. I coded in some sleep time between calls to avoid hitting that rate limit. I have never received that error.