向每个人发送 1 封电子邮件,其中包含他们的所有代码

Send 1 email to each person with all their codes

我需要编写一个脚本,向每个人发送一封电子邮件。 该电子邮件将具有该人的唯一代码。 每个人都可以获得任意数量的代码。

数据是这样的

Email,Codes
Email@dom.com,213
Email@dom.com,999
Email2@dom.com,111
Email2@dom.com,123
Email2@dom.com,643
Email2@dom.com,809
Email2@dom.com,722
Email3@dom.com,013

我觉得剧本应该是这样的。

#get the data
$PeopleAndCodes = Import-Csv C:\temp\PeopleCodes.csv

#Count how many groups of unique people
[array]$CountOfPeople = $PeopleAndCodes.email | Group-Object -noelement | Select-Object Count

#Loop through unique people
$Index = 0;
while ($Index -lt $CountOfPeople.count) {
    $Index++

#THIS BELOW EXITS BEFORE GETTING THROUGH ALL THE CODES FOR ONE PERSON
    [int]$DCodes = 0
    foreach ($DCodes in [int]$CountOfPeople[$DCodes].count) {
        $DCodes++

        Write-Host $DCodes DCODES
        Write-Host $CountOfPeople[$DCodes].count CountOfPeople
        Write-Host $PeopleAndCodes[$DCodes].codes
    }
}

问题是我的第二个循环在达到唯一人数后立即停止,然后转到下一个人。

我不明白为什么第二个循环没有通过代码然后给下一个人?

你非常接近,我会对你的代码做一些小的调整,我们就可以实现它。

首先,我们 select 代码列表中的所有唯一 e-mails,而不是通过数组进行索引。

$uniqueUsers = $PeopleAndCodes | select -Unique Email

接下来,我们可以 foreach 循环遍历 $uniqueUsers 的列表,并为每个找到匹配的代码。

foreach($uniqueUser in $uniqueUsers){
    $thisEmail = $uniqueUser.Email

    $matchingCodes = $PeopleAndCodes | Where Email -Match $uniqueUser.Email |
         Select-Object -ExpandProperty Codes

现在我们在这个循环中有一个 $thisEmail 变量,它包含用户的电子邮件地址,然后是用户所有匹配代码的数组,称为 $matchingCodes。我们也不需要通过这些索引。事实上,第二个循环可能导致了问题,因为 列表中的项目多于唯一用户

您的限制条件是唯一用户数,而不是列表中的项目数。

因此,为了避免混淆并获得所需的输出,只需完全删除第二个循环,因为它对我们没有帮助。

        Write-Host "Person - $thisEmail"
        Write-Host "Person has $($matchingCodes.Count) codes"
        $matchingCodes -join ","

输出

Person - Email@dom.com
Person has 2 codes
213,999
--------------------
Person - Email2@dom.com
Person has 5 codes
111,123,643,809,722

完成代码

$PeopleAndCodes = Import-Csv C:\temp\PeopleCodes.csv
$uniqueUsers = $PeopleAndCodes | select -Unique Email

foreach($uniqueUser in $uniqueUsers){
    $thisEmail = $uniqueUser.Email

    $matchingCodes = $PeopleAndCodes | where Email -Match $uniqueUser.Email | Select-Object -ExpandProperty Codes

    Write-Host "Person - $thisEmail"
    Write-Host "Person has $($matchingCodes.Count) codes"
    $matchingCodes -join ","

    Write-Host "--------------------"
}

我想指出以上是最佳答案。在评论中是另一个适用于我的原始代码的答案。

#get the data
$PeopleAndCodes = Import-Csv C:\temp\PeopleCodes.csv

#Count how many groups of unique people
[array]$CountOfPeople = $PeopleAndCodes.email | Group-Object -noelement | Select-Object Count

#Loop through unique people
$Index = 0;
while ($Index -lt $CountOfPeople.count) {
    $Index++

#This loops through each person and gets their code(s)
    [int]$DCodes = 0
    foreach ($DCodes in 0..[int]$CountOfPeople[$DCodes].count) {

        Write-Host $PeopleAndCodes[$DCodes].email
        Write-Host $PeopleAndCodes[$DCodes].codes
        $DCodes++
    }
}