gpt4 book ai didi

powershell - Exchange Online - Get-UserPhoto - 如何捕获非终止错误?

转载 作者:行者123 更新时间:2023-12-02 23:08:51 28 4
gpt4 key购买 nike

我正在尝试使用 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

接下来我尝试了 try, catch 但是非终止错误永远不会调用 catch 尽管网上有各种关于首先设置 $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

最佳答案

PowerShell 的错误处理是出了名的棘手,尤其是对于通过本地生成的代理脚本模块使用隐式远程处理的 cmdlet。

下面的习语提供了一种基于临时设置 $ErrorActionPreferenceStop globally 的解决方法(当然,您可以移动代码来恢复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 不同,后者会看到。

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

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

关于powershell - Exchange Online - Get-UserPhoto - 如何捕获非终止错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50298817/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com