首页 > 解决方案 > 在电子邮件正文的另一个变量中显示变量的值

问题描述

--Connect and open MYSQL Connection to the database
$strUser = "X"
$strPW = "Y"
$strDB = "Z"
$strserver = "dataserver"

[void][System.Reflection.ASsembly]::LoadWithPartialName("MySql.Data")
$conn = New-Object MySql.Data.MySqlClient.MySqlConnection
$cs = "server=$($strserver);port=3306;database=$($strdb);uid=$($struser);pwd=$($strPW)"
$conn.connectionstring = $cs
$conn.Open()

$query = "select * from users"


$cmd = new-object MySql.Data.MySqlClient.MySqlCommand($StoresNotPolledToday,$conn)
$da = new-object MySql.Data.MySqlClient.MySqlDataAdapter($cmd)
$ds = New-Object System.Data.DataSet
$recordcount = $da.Fill($ds, "users")

--Display the values from the query
$ds.Tables



-- Compile the e-mail
$From = "test@gmail.com"
[string[]]$To = "Me@gmail.com"
$Subject = "Test Subject"
$Body = "Test Body and text
$ds.Tables "

$SMTPServer = "smtp.gmail.com"
$SMTPPort = "587"
$password = "Password1" | ConvertTo-SecureString -asPlainText -Force
$username = "test@gmail.com"
$credential = New-Object System.Management.Automation.PSCredential($username,$password)
Send-MailMessage -From $From -to $To -Subject $Subject `
-Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl `
-Credential $credential 

我收到的电子邮件正文的最终结果是:“System.Data.DataSet” 我怎样才能强制它显示电子邮件正文中 $ds.Tables 中的值?

我尝试过:

$var = $ds.Tables

然后把这个 $var 放在电子邮件的 $body 中

$Body = "Test Body and text
    $var "

我在正文中收到的结果是:“用户”作为正文

标签: mysqldatabasepowershell

解决方案


我没有要测试的 mysql db,但您需要将 $ds.tables 转换为可以转换为至少一个 HTML 片段的对象,如果不是,只需转换为整个 HTML 页面:

$ds.tables | Convertto-HTML 

或者

$ds.tables | Convertto-Html -Fragment

如果这不能正确准确地显示数据(如果确实如此,PowerShell 将代表您进行大量数据转换),您需要获取 .Tables Collection 对象并将其转换为可以转换为 HTML 的对象分段:

我通常通过先将基础 Collection 对象转换为数组然后执行转换来完成此类工作

@($ds.tables) | Covnertto-Html

编辑1:

此外,在您的 Send-MailMessage cmdlet 上,您将要使用属性 -BodyAsHtml $true

编辑2:

以下是我建议的更清楚的编辑:

$arr = @($ds.Tables)  ## Have PowerShell change the type from a probably SqlDataTable to an Array



-- Compile the e-mail
$From = "test@gmail.com"
[string[]]$To = "Me@gmail.com"
$Subject = "Test Subject"
$Body = ($arr | ConvertTo-Html)  ## Convert to the array to an HTML page
$SMTPServer = "smtp.gmail.com"
$SMTPPort = "587"
$password = "Password1" | ConvertTo-SecureString -asPlainText -Force
$username = "test@gmail.com"
$credential = New-Object System.Management.Automation.PSCredential($username,$password)
Send-MailMessage -From $From -to $To -Subject $Subject -BodyAsHtml $true ` ## Added the flag to allow the email to be sent in HTML format
-Body $Body -SmtpServer $SMTPServer -port $SMTPPort -UseSsl `
-Credential $credential 

推荐阅读