自定义对象多行

时间:2014-03-20 18:14:55

标签: powershell pscustomobject

我创建了一个脚本来从AD中提取一些信息,我遇到的问题是辅助SMTP地址字段有多行。我想在新行中显示每个辅助SMTP。我的脚本输出看起来像{smtp:joe.rodriguez@con...

$searchBase = 'OU=Users,DC=Contoso,DC=LOCAL'

$users = Get-ADUser -filter 'enabled -eq $true' -SearchBase $searchBase |select -expand samaccountname

Foreach ($user in $users){ 
$Secondary = get-recipient -Identity $user -ErrorAction SilentlyContinue| select Name -ExpandProperty emailaddresses |? {$_.Prefix -like "SMTP" -and $_.IsPrimaryAddress -like "False"} |select -ExpandProperty $_.Smtpaddress 

New-Object -TypeName PSCustomObject -Property @{
Name = Get-ADUser -Identity $user -Properties DisplayName |select  -ExpandProperty DisplayName
"Login ID" = Get-ADUser -Identity $user -Properties SamAccountName |select -ExpandProperty SamAccountName
Primary = get-recipient -Identity $user -ErrorAction SilentlyContinue| select Name -ExpandProperty emailaddresses |? {$_.Prefix -like "SMTP" -and $_.IsPrimaryAddress -like "True"} |select -ExpandProperty Smtpaddress 
Secondary =  $Secondary 
  }
}

1 个答案:

答案 0 :(得分:1)

我个人制作一个数组,拉出你的用户列表,然后遍历每个用户的辅助SMTP地址,将每个条目的自定义对象添加到数组中。

$Userlist = @()

$searchBase = 'OU=Users,DC=Contoso,DC=LOCAL'
$users = Get-ADUser -filter 'enabled -eq $true' -SearchBase $searchBase -Properties DisplayName

Foreach ($user in $users){ 
    $Recip = get-recipient -Identity $user.samaccountname -ErrorAction SilentlyContinue| select Name -ExpandProperty emailaddresses |? {$_.Prefix -like "SMTP"}

    $Recip|? {$_.IsPrimaryAddress -like "False"} |select -ExpandProperty Smtpaddress |%{
        $UserList += New-Object -TypeName PSCustomObject -Property @{
            Name = $User.DisplayName
            "Login ID" = $User.SamAccountName
            Primary = $Recip|? {$_.IsPrimaryAddress -like "True"} |select -ExpandProperty Smtpaddress 
            Secondary =  $_
        }
    }
}

这个脚本(基于上面的脚本)也减少了我认为每个用户3个服务器查询的数量,所以它应该运行得更快。