I\'m trying to export a list of all users with no photo from our Exchange Online account using powershell. I cannot get it to work and have tried various methods.
G
PowerShell's error handling is notoriously tricky, especially so with cmdlets that use implicit remoting via a locally generated proxy script module.
The following idiom provides a workaround based on temporarily setting $ErrorActionPreference to Stop globally (of course, you may move the code for restoring the previous value outside the foreach loop), which ensures that even functions from different modules see it:
try {
# Temporarily set $ErrorActionPreference to 'Stop' *globally*
$prevErrorActionPreference = $global:ErrorActionPreference
$global:ErrorActionPreference = 'Stop'
$user | get-userphoto
} catch {
Write-Host "ERROR: $_"
$email= $user.userprincipalname
$name = $user.DisplayName
$office = $user.office
write-host "User photo not found...adding to list : $name, $email, $office"
$resultslist += $user
} finally {
# Restore the previous global $ErrorActionPreference value
$global:ErrorActionPreference = $prevErrorActionPreference
}
As for why this is necessary:
Functions defined in modules do not see the caller's preference variables - unlike cmdlets, which do.
The only outside scope that functions in modules see is the global scope.
For more information on this fundamental problem, see this GitHub issue.