0

我想foreach在电子邮件正文中发送 PowerShell 循环的结果。

变量的输出给了我想要的表格。当我尝试发送电子邮件时收到此错误消息。

Send-MailMessage:无法将“System.Object[]”转换为参数“Body”所需的类型“System.String”。不支持指定的方法。

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 = "user1@domain.com"
$emailfrom = "Do_not_reply@domain.com"

$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
4

1 回答 1

1

你想把你-Join的内容$message变成一个单一的字符串。试试这个:

Send-MailMessage -to $emailrecipients -subject 'Awesome Subject Here' -Body (-join $message) -SmtpServer mail-server.net -port 11 -FROM $emailfrom
于 2019-02-14T19:43:15.887 回答