【发布时间】:2018-10-22 06:06:15
【问题描述】:
我正在尝试使用 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
【问题讨论】:
-
在您的
try块中,尝试添加$local:ErrorActionPreference = 'Stop' -
According to the documentation cmdlet 应该支持common parameters。不过,我相信即使是非终止错误也会添加到
$Error变量中,所以你应该可以这样做:$Error.Clear(); command here; if ($Error) { } -
@TheIncorrigible1: Re global scope: 这是明智的 - 这就是为什么在我的回答中我 restore
finally块中的先前值 - 但是,至少设置它 暂时需要(所以我推测)在这种情况下解决脚本模块变量范围问题。请注意try不会创建单独的范围 -try块内的$local:ErrorActionPreference = 'Stop'对于其余的封闭函数/脚本仍然有效。 -
@mklement0 我原以为
try创建了自己的块作用域(由于使用了脚本块语法)。很高兴知道,谢谢! -
对于尝试此操作的其他人,事实证明 Get-Mailbox 具有 HasPicture 属性 - 查询此属性比检查异常要快得多。
标签: powershell office365 exchange-server