Jeremy F.
Jeremy F.

Reputation: 1868

foreach loop results into email body

I want to send the results of a PowerShell foreach loop in the body of an email.

The output of the variable gives me the table I want. I get this error message when I try to send the email.

Send-MailMessage : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'Body'. Specified method is not supported.

function Invoke-MSSQLCommand {
    [CmdletBinding()]
    Param(
        [System.String]$ConnectionString,
        [System.String]$SQLCommand
    )

    $V_cn = New-Object System.Data.SqlClient.SqlConnection("Data Source=$ConnectionString;Integrated Security=SSPI;Initial Catalog=master;Application Name=TEST_1;");
    $V_cn.Open()
    $command_v = $V_cn.CreateCommand()
    $command_v.CommandText = $SQLCommand;
    $result_v = $command_v.ExecuteReader()
    $table_v = New-Object "System.Data.DataTable" "MyResultSet"
    $table_v.Load($result_v)
    $V_cn.Close();
    $V_cn.Dispose();

    return ,$table_v
}; #function end

$myobject = Invoke-MSSQLCommand -ConnectionString "server.domain,1433" -SQLCommand "Select [TimeStamp], [Computer Name] from something.dbo.table";

$emailrecipients = "[email protected]"
$emailfrom = "[email protected]"

$message = foreach ($one in $myobject) {
    #$temp += "TimeStamp = " + $one.TimeStamp + " Computer Name = " + $one.'Computer Name'
    "TimeStamp = " + $one.TimeStamp + " Computer Name = " + $one.'Computer Name' + "`r "
}

$message

Send-MailMessage -To $emailrecipients -Subject 'Awesome Subject Here' -Body $message -SmtpServer mail-server.net -Port 11 -From $emailfrom

Upvotes: 0

Views: 1823

Answers (1)

Steve Boyd
Steve Boyd

Reputation: 1357

You want to -Join the content of your $message into a single string. Try this:

Send-MailMessage -to $emailrecipients -subject 'Awesome Subject Here' -Body (-join $message) -SmtpServer mail-server.net -port 11 -FROM $emailfrom

Upvotes: 1

Related Questions