结合Powershell的结果

时间:2013-02-14 21:57:30

标签: powershell

我有一个powershell函数,可以从Active目录中获取信息。它将发送一封电子邮件,电子邮件正文将包含与该电子邮件地址关联的任何组。如下所示,test@email.com列出了两次。而是发送2封电子邮件到test@email.com,我宁愿发送一封电子邮件与两个团体在一起。我怎样才能做到这一点?感谢

email               group
test@email.com      number1
test@email.com      number2
notet@email.com     number1
hello@email.com     number3

(Get-ADUser -Identity lbono –Properties MemberOf | Select MemberOf).MemberOf | Get-ADGroup -Properties ManagedBy | Select Name, ManagedBy, Distinguishedname, GroupCategory |

Where-Object {
$_.Distinguishedname -notlike "*Unity*" -and $_.Distinguishedname -notlike "*DynastyGroups*" -and $_.name -notlike "*Technical Library*" }|
ForEach-Object {
If ($_.ManagedBy) {
$result = New-Object PSObject
Add-Member -input $result NoteProperty 'Group Name' $_.Name
Add-Member -input $result NoteProperty 'Managed By' ((Get-ADUser -Identity $_.ManagedBy).givenName + ' ' + ((Get-ADUser -Identity $_.ManagedBy).surName))
Add-Member -input $result NoteProperty 'Email' (Get-ADUser -Identity $_.ManagedBy -Properties mail).Mail
Add-Member -input $result NoteProperty 'Group Type' $_.GroupCategory
Write-Output $result
}

} | select 'Group Name','Managed By','Email','Group Type' | sort 'Managed By'

2 个答案:

答案 0 :(得分:1)

我认为这是Group-Object cmdlet的完美用例。 显示如何利用它的代码段:

@'
email,group
test@email.com,number1
test@email.com,number2
notet@email.com,number1
hello@email.com,number3
'@ | ConvertFrom-Csv | Group-Object email | foreach {
    "To: {0} Body: {1}" -f 
        $_.Name, 
        (($_.Group | foreach { $_.group }) -join ', ')
}

替代方案:使用哈希表:

$mails = @{}
@'
email,group
test@email.com,number1
test@email.com,number2
notet@email.com,number1
hello@email.com,number3
'@ | ConvertFrom-Csv | ForEach-Object {
    if ($mails.ContainsKey($_.email)) {
        $mails."$($_.email)" += ", $($_.group)"
    } else {
        $mails."$($_.email)" = $_.group
    }
}

$mails.GetEnumerator() | ForEach-Object {
    "To: {0} Body: {1}" -f $_.Key, $_.Value
}

答案 1 :(得分:0)

由于没有指定任何内容,我假设你的函数My-Function返回一个对象数组,每个电子邮件有一个对象+组合。 此外,我假设电子邮件和组存储在名为emailgroup的属性中。

My-Function | Group-Object Email | % { 
    New-Object psobject -Property @{
        Email = $_.Name
        Groups = ($_.Group | select -ExpandProperty Group)
    }
}