我需要撰寫一個腳本,向每個人發送一封電子郵件。該電子郵件將具有此人的唯一代碼。每個人都可以獲得任意數量的代碼。
資料看起來像這樣
Email,Codes
[email protected],213
[email protected],999
[email protected],111
[email protected],123
[email protected],643
[email protected],809
[email protected],722
[email protected],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
}
}
問題是,一旦達到唯一人數,我的第二個回圈就會停止,然后移動到下一個人。
我不明白為什么第二個回圈沒有通過代碼然后傳遞給下一個人?
uj5u.com熱心網友回復:
你非常接近,我會對你的代碼做一些小的調整,我們可以得到它。
首先,讓我們從代碼串列中選擇所有唯一的電子郵件,而不是通過陣列進行索引。
$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
現在我們在這個回圈中有一個$thisEmailvar 保存用戶的電子郵件地址,然后是一個包含用戶所有匹配代碼的陣列,稱為$matchingCodes. 我們也不需要通過這些索引。事實上,第二個回圈可能會導致問題,因為串列中的專案比唯一用戶多。
您的限制條件是唯一用戶數,而不是串列中的專案數。
因此,為了避免混淆并獲得所需的輸出,只需完全洗掉第二個回圈,因為它對我們沒有幫助。
Write-Host "Person - $thisEmail"
Write-Host "Person has $($matchingCodes.Count) codes"
$matchingCodes -join ","
給出一個輸出
Person - [email protected]
Person has 2 codes
213,999
--------------------
Person - [email protected]
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 "--------------------"
}
uj5u.com熱心網友回復:
我想指出,雖然上面是最好的答案。評論中的另一個答案也適用于我的原始代碼。
#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
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/475909.html
標籤:电源外壳
