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

前端 未结 2 1646
逝去的感伤
逝去的感伤 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.

提交回复
热议问题