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 {
$_
}
}
}