在PowerShell中允许二维数组中的重复值

问题描述

我正在尝试从Exchange Online生成邮箱权限的报告。这是代码

$SendAs = @()
$MailBoxes = Get-mailBox | where {$_.Identity -notlike "discoverySearchMailBox*"}

Foreach ($MB in $MailBoxes) {
    $SendAstemp = Get-RecipientPermission $MB.userprincipalname | select identity,Trustee,AccessRights | `
        Where-Object {$_.Trustee -notlike "*\Self" -and $_.Trustee -notlike "S-1-5*"}
    if ($SendAstemp) {
        $SendAs += New-Object psobject -Property @{
            Identity=$SendAstemp.identity
            MailBox=$MB.primarysmtpaddress
            Trustee=$SendAstemp.Trustee
            AccessRights=$SendAstemp.AccessRights
        }
    }
}

问题是输出($ SendAs)是这个;

MailBox              Trustee                                 AccessRights           Identity
[email protected]    {[email protected],[email protected]}    {SendAs,SendAs}       {shared,shared}

它将“共享”的多个受托者权限添加到单行。我想要的是这个

MailBox              Trustee                                 AccessRights           Identity
[email protected]    [email protected]                        SendAs                 shared
[email protected]    [email protected]                        SendAs                 shared

我该如何实现?

解决方法

首先,avoid using the increase assignment operator (+=) to create a collection的价格昂贵。意思是,每次迭代都会变得更加昂贵。请改用PowerShell管道。

对于您的特定问题,您可以简单地遍历受托人,例如:

$Mailboxes = Get-mailbox | where {$_.Identity -notlike "DiscoverySearchMailbox*"}

$SendAs = Foreach ($MB in $Mailboxes) {
    $SendAsTemp = Get-RecipientPermission $MB.userprincipalname | select identity,Trustee,AccessRights |
        Where-Object { $_.Trustee -notlike "*\Self" -and $_.Trustee -notlike "S-1-5*" }
    if ($SendAsTemp) {
        Foreach ($Trustee in @($SendAsTemp.Trustee)) {
            New-Object psobject -Property @{
                Identity = $SendAsTemp.identity
                Mailbox = $MB.primarysmtpaddress
                Trustee = $Trustee
                AccessRights = $SendAsTemp.AccessRights
            }
        }
    }
}

(请注意,在此示例中,如果根本没有受托人,则不会列出整个邮箱条目。)