【问题标题】:PowerShell to list of UPNs based on specific Wildcard searchPowerShell 根据特定通配符搜索列出 UPN
【发布时间】:2020-02-20 09:45:18
【问题描述】:

我需要修改以下脚本,该脚本部分工作。

它基本上是查询Office 365用户、联系人、组和已删除用户,然后将其与用户输入匹配,然后在找到时将其显示在Out-GridView上。

Try { 
    Install-Module MSOnline -ErrorAction Stop
    Import-Module MSOnline -ErrorAction Stop 

    $UserCredential = Get-Credential
    Connect-MsolService -Credential $UserCredential
}
Catch { Write-Warning "Unable to load Microsoft Office 365 module because $($Error[0])"; Exit }

$UPN = Read-Host -Prompt "Please enter the User Principal Name to search (wildcard accepted)"
If ($UPN) {
    $UPN = $search
    $MSOLActiveUsers = Get-MsolUser -All
    $MSOLDeletedUsers = Get-MsolUser -All -ReturnDeletedUsers
    $MSOLGroups = Get-MsolGroup -All
    $MSOLContacts = Get-MsolContact -All
    $MSOLRecipients = Get-Recipient -ResultSize Unlimited​

    $MSOLCombinedResults = $MSOLActiveUsers + $MSOLDeletedUsers + $MSOLGroups + $MSOLContacts + $MSOLRecipients
    ​
    $MSOLCombinedResults | Where-Object { $_.emailaddresses -match $search -or $_.emailaddress -match $search -or $_.userprincipalname -eq $search -or $_.proxyaddresses -match $search }

    Switch ($MSOLCombinedResults.Count) {
        0 { Write-Warning "No user account with a SamAccountName matching '$($UPN)' found!" }
        1 { $MSOLCombinedResults }
        default { $MSOLCombinedResults | Out-GridView -Title "Please select a user" -OutputMode Single }
    }
}

上述脚本的问题是结果总是无意义的长Gridview?

【问题讨论】:

  • 你能告诉我们$MSOLCombinedResults[0]的内容吗?

标签: powershell scripting active-directory office365 windows-scripting


【解决方案1】:

注意:您的脚本缺少连接到 Exchange Online,这是 Get-Recipient 所必需的,但我假设您这样做了,但只是忘记添加您的问题。


首先,你在这一行过滤$MSOLCombinedResults

 $MSOLCombinedResults | Where-Object (...)

然后你通过管道传递给Out-GridView 未过滤的数组:

$MSOLCombinedResults | Out-GridView (...)

您忘记的是保存过滤后的数组,然后对其进行操作。 PowerShell 不会自动执行此操作,因此您应该使用以下内容:

$filteredResults = $MSOLCombinedResults | Where-Object { $_.emailaddresses -match $search -or $_.emailaddress -match $search -or $_.userprincipalname -eq $search -or $_.proxyaddresses -match $search }

Switch ($filteredResults .Count) {
  # do something
}

另一件事是$MSOLCombinedResults 包含多种类型的对象,因此您应该在输出它之前选择所需的属性(出于性能原因,最好更早地选择它们)。

您感兴趣的数据如下:

  • 来自Get-MsolUser:UserPrincipalName(字符串)、ProxyAddresses(数组)
  • 来自Get-MsolGroup:EmailAddress(字符串)、ProxyAddresses(数组)
  • 来自Get-MsolContact:EmailAddress(字符串),ProxyAddresses(数组,可选,因为我通常看不到此值设置)
  • 来自Get-Recipient:EmailAddresses(数组,注意复数),ExternalEmailAddress(SMTP:xxx 格式的字符串),PrimarySmtpAddress(字符串)

您必须相应地修改您的过滤器,然后使用Select-ObjectOut-GridView 输出所需的结果。查看calculated properties,您可能希望重命名/转换一些属性以便于过滤。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-04
    • 2018-01-17
    相关资源
    最近更新 更多