Powershell Script to read only 1 line from input csv

Shaz 1 Reputation point
2022-12-02T09:50:33.22+00:00

I am using powershell script that reads input csv, and sends email notifications to email address mentioned in email column. As email address mentioned in each row is same, script should send only 1 email. As in my current script I am using foreach loop, it is sending email notification for each row in csv. For example, if csv has 5 rows, and same email address is mentioned in all 5 rows, it is sending 5 email notifications. How do I modify for loop, so that script only reads 1 row and sends email notification only once. Attaching my current script
$Users = Import-Csv -path "G:\Users.csv"
foreach($user in $users) {
$bodytxt = @"
Hello,

Email Body.  
  
"@  
  
$EmailFrom = 'xyz@outlook.com'  
$EmailTo = $user.AppOwner  
$EmailSubject = "Review Notification"   
$EmailBody = "$bodytxt"  
$SMTPServer = 'smtp-relay.com'  

$EncryptedPasswordFile = "$home\Documents\PSCredential\MailJet.txt"  
$username="abc@outlook.com"   
$password = Get-Content -Path $EncryptedPasswordFile | ConvertTo-SecureString  
$credential = New-Object System.Management.Automation.PSCredential($username, $password)  
  
Send-MailMessage -ErrorAction Stop -from "$EmailFrom" -to "$EmailTo" -subject "$EmailSubject" -body "$EmailBody" -SmtpServer "$SMTPserver" -Priority  "Normal" -Credential $credential -Port 587 -UseSsl  
  
}  
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,576 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. MotoX80 34,686 Reputation points
    2022-12-02T13:36:24.643+00:00

    Since you only reference $user.AppOwner you can change the import to this.

    $Users = Import-Csv -path "G:\Users.csv" | Select-Object -Property AppOwner -Unique  
    
    0 comments No comments

  2. Rich Matheisen 47,466 Reputation points
    2022-12-02T16:02:59.46+00:00

    Or this:

    $User = Import-Csv -path "G:\Users.csv" | Select-Object -Expand AppOwner -First 1  
    

    Then change line #6 to $EmailTo = $User

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.