#Set-MgUserPhotoContent Error on Every Other Call

2 messages · Page 1 of 1 (latest)

charred kettle
#

I have a script that takes jpeg files from a folder and updates the corresponding user's photo in M365 using the Set-MgUserPhotoContent cmdlet. I'm getting Error while copying content to a stream on every other run within the foreach loop. I don't see anything about rate limiting, and the same files run fine on subsequent runs, and it appears to consistently fail with every other call inside the foreach loop. My logs look like this:

Processing [<JDoe>]
Successfully updated photo for [<JDoe>]

Processing [<MSmith>]
ERROR in <ScriptName.ps1> on line 29: Error while copying content to a stream.

Processing [<MJones>]
Successfully updated photo for [<MJones>]

Processing [<TWilson>]
ERROR in <ScriptName.ps1> on line 29: Error while copying content to a stream.

Processing [<BSmith>]
Successfully updated photo for [<BSmith>]

The code (stripped of logging/error handling)

#Already called Connect-MgGraph successfully
$ImagesPath = '\\Server\Share\Active'
$Images = Get-ChildItem $ImagesPath -Filter *.jpg
Foreach ($Item in $Images) {
    $UserObj = Get-ADUser -Filter "SamAccountName -eq '$($Item.BaseName)'"
    If ($UserObj) {
        $UPN = $UserObj.UserPrincipalName
        Try {
            Set-MgUserPhotoContent -UserId $UPN -InFile $Item.FullName -ErrorAction Stop
        } Catch {
            $_
        }
    }
}
#

This is the first part of the full exception/innerexception message when I output it:

System.Net.Http.HttpRequestException: 
Error while copying content to a stream._x000D__x000A_ ---> 
System.IO.IOException: The parameter is incorrect. : '\\Server\Share\Active\UserID.jpg'_x000D__x000A_
    at System.IO.RandomAccess.ReadAtOffset(SafeFileHandle handle, Span`1 buffer, Int64 fileOffset)_x000D__x000A_
    at Microsoft.Win32.SafeHandles.SafeFileHandle.ThreadPoolValueTaskSource.ExecuteInternal()_x000D__x000A_--- 

Would a simple Start-Sleep inside the loop help here? The script usually only processes a couple dozen files (at most), so sleeping for 500ms or 1-2sec in the foreach loop won't negatively impact the utility of the script.