I am trying to query a SQL database and then loop through each of the data sets to send an email with data.
Below is a sample data set - so for record 1, my goal is to send an email to [email protected] with the policy information for that specific record and so on for the remaining records.
PolicyNumber PSN TransactionPremium EmailAddress Record
ABC DE3 0000012183 00 8636692 14109 [email protected] 1
FGH JI3 0000012183 00 8636693 -14199 [email protected] 2
KLM NO3 0000000774 03 8556541 -1664 [email protected] 3
PRS TU3 0000000943 03 8579971 0 [email protected] 4
HCA HO3 0000000969 03 8603944 -1425 [email protected] 5
But after returning the data from the query, I cannot figure out how to loop through each record and send the email.
$Instance = "sqlinstancename"
$Database = "databasename"
$SQL = @'
SELECT TOP (5) PolicyNumber, PSN, CAST(TransactionPremium AS DECIMAL(19,4)) AS TransactionPremium, EmailAddress
FROM dbo.TableName ORDER BY BatchDate DESC
'@
Invoke-DbaQuery -SqlInstance $Instance -Database $Database -Query $SQL
I assume it will be something along the lines of:
ForEach ($i in i)
{
Send-MailMessage -From "[email protected]" -To $EmailAddress -Subject "Test" -BodyAsHTML $PolicyNumber"
}
Could I get some assistance on how to accomplish this task?