创建足够 headers 以容纳所有结果

Create enough headers to accommodate all results

我的脚本在这里:

$Results = @()
Get-Mailbox | % {
  $o = New-Object -Type PSCustomObject -Property @{
         'DisplayName'         = $_.DisplayName
         'alias'               = $_.alias
         'UserPrincipalName'   = $_.UserPrincipalName
         'PrimarySmtpAddress'  = $_.PrimarySmtpAddress
         'PrimaryProxyAddress' = ($_.EmailAddresses) -cmatch "SMTP:" -replace '^smtp:' -join ' ' 
       }

  $i = 1
  $_.EmailAddresses -cmatch "smtp:" | % {
    $o | Add-Member -Type NoteProperty -Name "OtherProxyAddress$i" `
      -Value ($_ -replace '^smtp:')
    $i++
  }

  $Results += $o
}

$results| ConvertTo-Csv -Delimiter "`t" -NoTypeInformation | clip

问题出在我转换为 CSV 时。转换为 CSV 时,它需要第一个邮箱有多少 OtherProxyAddress 在那里。如果第一个邮箱中有两个 OtherProxyAddress,它将使用它并为 CSV 文件创建标题。但是,某些邮箱可能有 2 个以上的 OtherProxyAddress 字段。在这种情况下,当我在 Excel 中打开 CSV 时,我错过了具有两个以上 OtherProxyAddress 字段的邮箱的其他条目。

我希望能够以 CSV 格式捕获,因此我可以粘贴到 Excel 中,顶部的 headers 足以匹配具有最多 OtherProxyAddress 字段的邮箱。

这不是我最好的工作,但它似乎完成了工作。我想我可能已经更改了您想要的属性,但我需要重新安排一些东西以获得工作原理的动态部分。

$all = Get-Mailbox
$maxProxyIndex = $all | Select EmailAddresses | Where-Object{$_.EmailAddresses -cmatch "smtp"} | ForEach-Object{
    ($_.EmailAddresses -split "," | Where-Object{$_  -cmatch "smtp"} | Measure-Object).Count
} | Measure-Object -Maximum | Select -ExpandProperty Maximum

$propertyOrder = "DisplayName","Alias","UserPrincipalName","PrimarySmtpAddress" + (1..$maxProxyIndex | ForEach-Object{"ProxyAddress$_"})

$all | ForEach-Object{
    $props = @{
         'DisplayName'         = $_.DisplayName
         'alias'               = $_.alias
         'UserPrincipalName'   = $_.UserPrincipalName
         'PrimarySmtpAddress'  = $_.PrimarySmtpAddress
       }
    $proxyAddresses = @(($_.EmailAddresses -split ","| Where-Object{$_  -cmatch "smtp"})) -replace "^smtp:"
    For($proxyIndex = 1; $proxyIndex -le $maxProxyIndex;$proxyIndex++){
        $props."ProxyAddress$proxyIndex" = If($proxyAddresses){$proxyAddresses[$proxyIndex - 1]}
    }

    New-Object -TypeName PSCustomObject -Property $props
} | Select-Object $propertyOrder | ConvertTo-Csv -Delimiter "`t" -NoTypeInformation | Clip

首先,就像你说的,我们需要找出代理地址数量最多的邮箱,也就是$maxProxyIndex。我们收集所有邮箱数据,因为我们需要对其进行两次解析。一次用于最大索引,第二次用于整体输出。

对于$maxProxyIndex,我们获取每个邮箱的emailaddresses并过滤辅助smtp电子邮件。然后我们使用 Measure-Object -Maximum 来得到那个神奇的数字。

当我们在主循环中创建对象输出时,我们需要始终创建其他代理属性,即使它们不存在。

您会看到我们正在使用 $propertyOrder,这很重要,因为属性的动态创建不会在输出中给出正确的顺序。

Ansgar Wiechers' Comment

None 是必需的,因为您可以利用 Excel 功能来实现类似的目标。根据他的评论:

Addendum: when pasting the data into Excel, you could use Text to Columns for splitting a column with delimited values. You just need to make sure to have enough blank columns right of the column with your data (so you don't overwrite other values)