CSV to Dynamic Tables to HTML Email

2020-05-05 17:59发布

问题:

I am trying to write a script that

  1. reads a CSV file that has 3 columns: email, server, date. There are duplicate email addresses, but no duplicate servers

  2. makes a table for each distinct email address from CSV file

  3. sends one email to each distinct email address from CSV file with a list of servers and their dates in an HTML table format.

$Email_Template = "C:\template.html"
[String] $Email_Template = Get-Content "Email_Template"

$csv = Import-Csv "C:\file.csv"
$emailarray = @()

foreach ($test in $csv) {
    $emailobject = New-Object PSObject |
        Add-Member -Name Email -Value $test.Email -MemberType NoteProperty -PassThru |
        Add-Member -Name Email -Value $test.Server -MemberType NoteProperty -PassThru |
        Add-Member -Name Email -Value $test.Date -MemberType NoteProperty -PassThru

    $emailarray += $emailobject
}
foreach ($test in $EmailArray) {
    try {
        $Parameters = @{
            #email variables (from cc, etc.)
            bodyashtml = $true
        }

        $Parameters += @{to = $test.Email}
        Send-MailMessage @Parameters -ErrorAction Stop
    }
}

I'm having success creating the tables by email name, but am having trouble referencing those to be added to the email associated with them.

回答1:

You are losing the value of the email property of the $emailobject because you are calling Add-Member multiple times with the same name.

A cleaner way to construct the object is to use a dictionary:

$emailobject = New-Object PSObject -Property @{"Email"=$test.Email; "Server" = $test.Server ; "Date" = $test.Date}

Will create an email object with 3 properties.