我想在电子邮件正文中发送PowerShell foreach
循环的结果。
变量的输出给了我想要的表。尝试发送电子邮件时收到此错误消息。
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
答案 0 :(得分:1)
您要将-Join
的内容$message
放入单个字符串中。试试这个:
Send-MailMessage -to $emailrecipients -subject 'Awesome Subject Here' -Body (-join $message) -SmtpServer mail-server.net -port 11 -FROM $emailfrom