Exchange Online - Get-UserPhoto - how to catch non terminating error?

前端 未结 2 1645
逝去的感伤
逝去的感伤 2020-12-20 02:40

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

相关标签:
2条回答
  • 2020-12-20 03:09

    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.

    0 讨论(0)
  • 2020-12-20 03:22

    You can throw your own error like so:

    try {
        $error.Clear()
        $user | Get-UserPhoto 
        if ($error[0].CategoryInfo.Reason -eq "UserPhotoNotFoundException") {throw "UserPhotoNotFoundException" }
    } catch {
        #code
    }
    
    0 讨论(0)
提交回复
热议问题