首页 > 解决方案 > Exchange Online - Get-UserPhoto - 如何捕获非终止错误?

问题描述

我正在尝试使用 powershell 从我们的 Exchange Online 帐户中导出所有没有照片的用户列表。我无法让它工作并尝试了各种方法。

当不存在配置文件时,Get-UserPhoto 会返回此异常。

Microsoft.Exchange.Data.Storage.UserPhotoNotFoundException: There is no photo stored here.

首先,我尝试对命令使用Errorvariable但收到:

A variable that cannot be referenced in restricted language mode or a Data section is being referenced. Variables that can be referenced include the following: $PSCulture, $PSUICulture, $true, $false, and  $null.
+ CategoryInfo          : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : VariableReferenceNotSupportedInDataSection
+ PSComputerName        : outlook.office365.com

接下来我尝试 了尝试,捕获但非终止错误从未调用捕获,尽管在线遵循了各种方法来首先设置$ErrorActionPreference 。

有任何想法吗 ?这是脚本:

 $UserCredential = Get-Credential
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection
Import-PSSession $Session 

$timestamp = $timestamp = get-date -Format "dd/M/yy-hh-mm"
$outfile = "c:\temp\" + $timestamp + "UserswithoutPhotos.txt"




$resultslist=@()
$userlist = get-user -ResultSize unlimited -RecipientTypeDetails usermailbox | where {$_.accountdisabled -ne $True}


Foreach($user in $userlist)
{
    try
    {

        $user | get-userphoto -erroraction stop 
    }
    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

    }
}
$resultslist | add-content $outfile 
$resultslist

标签: powershelloffice365exchange-server

解决方案


众所周知,PowerShell 的错误处理非常棘手,尤其是对于通过本地生成的代理脚本模块使用隐式远程处理的 cmdlet。

以下成语提供了一种基于临时设置$ErrorActionPreferenceStop 全局的解决方法(当然,您可以将用于恢复先前值的代码移到foreach循环之外),从而确保即使来自不同模块的函数也可以看到它:

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

}

至于为什么这是必要的:

  • 模块中定义的函数看不到调用者的偏好变量 - 与cmdlet不同,后者可以。

  • 模块中的函数看到的唯一外部范围是全局范围。

有关此基本问题的更多信息,请参阅此 GitHub 问题


推荐阅读