0

我有一个从 Active Directory 获取信息的 powershell 函数。它将发送一封电子邮件,电子邮件的正文将包含与该电子邮件地址关联的任何组。正如您在下面看到的,test@email.com 被列出了两次。与其向 test@email.com 发送 2 封电子邮件,我更愿意在正文中发送一封包含两个组的电子邮件。我怎样才能做到这一点?谢谢

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'
4

2 回答 2

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
}
于 2013-02-14T22:09:06.077 回答
0

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

My-Function | Group-Object Email | % { 
    New-Object psobject -Property @{
        Email = $_.Name
        Groups = ($_.Group | select -ExpandProperty Group)
    }
}
于 2013-02-14T22:14:27.283 回答