在电子邮件中没有查询结果

时间:2015-01-25 05:31:52

标签: mysql powershell

这是我的powershell脚本。我正在尝试将查询的结果导出到电子邮件正文中。但是,除了表头之外,电子邮件不包含任何内容。任何人都可以帮助解决错误/不完整的问题吗?

# Create a DataTable
$table = New-Object system.Data.DataTable "bugs"
$col1 = New-Object system.Data.DataColumn bug_id,([string])
$col2 = New-Object system.Data.DataColumn bug_status,([string])
$col3 = New-Object system.Data.DataColumn resolution,([string])
$col4 = New-Object system.Data.DataColumn short_desc,([string])
$col5 = New-Object system.Data.DataColumn deadline,([string])
$table.columns.add($col1)
$table.columns.add($col2)
$table.columns.add($col3)
$table.columns.add($col4)
$table.columns.add($col5)

# This code defines the search string in the database table

$SQLQuery = "SELECT bug_id, bug_status, resolution, short_desc, deadline FROM bugs WHERE ( bug_status IN ( 'RESOLVED', 'VERIFIED', 'INTEST' ) AND deadline BETWEEN CURDATE() AND DATE_ADD(CURDATE(), INTERVAL 30 DAY) ) OR ( bug_status IN ( 'RESOLVED', 'VERIFIED', 'INTEST' ) AND deadline BETWEEN DATE_SUB(CURDATE(), INTERVAL 30 DAY) AND CURDATE() )
ORDER BY deadline ASC "

# This code connects to the SQL server and retrieves the data
$MySQLAdminUserName = 'user_name'
$MySQLAdminPassword = 'password'
$MySQLDatabase = 'mantis'
$MySQLHost = '<HOSTNAME>'
$ConnectionString = "server=" + $MySQLHost + ";port=3306;uid=" + $MySQLAdminUserName + ";pwd=" + $MySQLAdminPassword + ";database="+$MySQLDatabase

[void][system.reflection.Assembly]::LoadFrom("C:\Program Files (x86)\Devolutions\Remote Desktop Manager Free\MySQL.Data.dll")
$Connection = New-Object MySql.Data.MySqlClient.MySqlConnection
$Connection.ConnectionString = $ConnectionString
$Connection.Open()

$Command = New-Object MySql.Data.MySqlClient.MySqlCommand($SQLQuery, $Connection)
$DataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($Command)
$DataSet = New-Object System.Data.DataSet
$RecordCount = $dataAdapter.Fill($dataSet, "data")
$DataSet.Tables[0]  

# Create an HTML version of the DataTable
$html = "<table><tr><td>bug_id</td><td>bug_status</td><td>resolution</td><td>short_desc</td><td>deadline</td></tr>"
foreach ($row in $table.Rows)
{ 
    $html += "<tr><td>" + $row[0] + "</td><td>" + $row[1] + "</td></tr>" + "</td></tr>" + $row[2] + "</td></tr>"
}
$html += "</table>"

# Send the email
$smtpserver = "<SMTPSERVER>"
$from = "test@test.com"
$to = "test2@test.com"
$subject = "Hello"
$body = "Hi there,<br />Here is a table:<br /><br />" + $html
Send-MailMessage -smtpserver $smtpserver -from $from -to $to -subject $subject -body $body -bodyashtml

2 个答案:

答案 0 :(得分:2)

您可能还有其他问题,但日期算术肯定是一个问题。

MySQL对日期算术有非常奇怪的规则。 CURDATE()的值不是日期。它可以是字符串或数字。在数字上下文中(CURDATE() + 9是数字上下文),然后它返回一个数字。

因此,2015-01-25日期将返回整数20150125.您可以在SQL Fiddle here上看到此现象。此值加上九是20150134.不是有效日期而不是您所期望的。

最简单的解决方法是使用date_add()

SELECT  bug_id, bug_status, resolution, short_desc, deadline
FROM bugs
WHERE bug_status IN ('RESOLVED') AND
      deadline BETWEEN CURDATE() AND date_add(CURDATE(), interval 9 day)

答案 1 :(得分:1)

我能够从多个来源将它们放在一起,这些来源似乎适用于您插入的任何mySQL查询。我想我会分享,以防其他人觉得它有用。从我至少测试的内容看似可靠。您不需要以这种方式使用SQL逻辑构建HTML表。

## -- This will download the needed PS module and load it accordingly and then prompt you to save the mySQL credential to make the connection to the data source
## -- Run PowerShell as administrator
## https://mcpmag.com/articles/2016/03/02/querying-mysql-databases.aspx

Invoke-WebRequest  -Uri https://github.com/adbertram/MySQL/archive/master.zip -OutFile  'C:\Users\user\desktop\MySQL.zip'
$modulesFolder =  'C:\Program Files\WindowsPowerShell\Modules'
Expand-Archive -Path  C:\Users\user\desktop\MySQL.zip -DestinationPath $modulesFolder
Rename-Item -Path  "$modulesFolder\MySql-master" -NewName MySQL

$dbCred =  Get-Credential
Connect-MySqlServer  -Credential $dbcred -ComputerName 'localhost' -Database sakila
## Enter the mySQL username and password when prompted

Invoke-MySqlQuery  -Query 'SELECT * FROM actor'
## --This will run automated after the PS module used to make the mySQL is already loaded and not prompt for credential to allow non-interactive runs
## --Embedded credential used here

$secpasswd = ConvertTo-SecureString “password” -AsPlainText -Force
$dbCred = New-Object System.Management.Automation.PSCredential (“root”, $secpasswd)

Connect-MySqlServer  -Credential $dbcred -ComputerName 'localhost' -Database sakila
Invoke-MySqlQuery  -Query 'SELECT * FROM actor LIMIT 5'
## This runs the Function to do the alternating row colors in the HTML table
Function Set-AlternatingRows {
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory,ValueFromPipeline)]
        [string]$Line,

        [Parameter(Mandatory)]
        [string]$CSSEvenClass,

        [Parameter(Mandatory)]
        [string]$CSSOddClass
    )
    Begin {
        $ClassName = $CSSEvenClass
    }
    Process {
        If ($Line.Contains("<tr><td>"))
        {   $Line = $Line.Replace("<tr>","<tr class=""$ClassName"">")
            If ($ClassName -eq $CSSEvenClass)
            {   $ClassName = $CSSOddClass
            }
            Else
            {   $ClassName = $CSSEvenClass
            }
        }
        Return $Line
    }
}

## -- This portion builds the HTML table based on the SQL query which you can change accordingly for your needs
## https://community.spiceworks.com/scripts/show/1745-set-alternatingrows-function-modify-your-html-table-to-have-alternating-row-colors
## https://philerb.com/2011/11/sending-mail-with-powershell/
## https://thesurlyadmin.com/2013/01/21/how-to-create-html-reports/

$Title  = "My Report Title" 
$Header = @"
<style>
TABLE {border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}
TH {border-width: 1px;padding: 3px;border-style: solid;border-color: black;background-color: #6495ED;}
TD {border-width: 1px;padding: 3px;border-style: solid;border-color: black;}
.odd  { background-color:#ffffff; }
.even { background-color:#dddddd; }
</style>
<title>
$Title
</title>
"@
$Pre = "<b>Table Title"
$Post = "<b>Table Footer"

$html = Invoke-MySqlQuery -Query 'SELECT * FROM actor LIMIT 5' | 
Select * -ExcludeProperty RowError, RowState, HasErrors, Name, Table, ItemArray | 
ConvertTo-HTML -Head $Header -PreContent $Pre -PostContent $Post | 
Set-AlternatingRows -CSSEvenClass even -CSSOddClass odd

$emailSmtpServer = "smtp.gmail.com"
$emailSmtpServerPort = "587"
$emailSmtpUser = "Username"
$emailSmtpPass = "Password"

$emailMessage = New-Object System.Net.Mail.MailMessage
$emailMessage.From = "mailbox@gmail.com"
$emailMessage.To.Add( "mailbox@gmail.com" )
$emailMessage.Subject = "Test email from PowerShell"
$emailMessage.IsBodyHtml = $true
$emailMessage.Body = @"
This is the body of the message.<br /><br /> $html 
"@

$SMTPClient = New-Object System.Net.Mail.SmtpClient( $emailSmtpServer , $emailSmtpServerPort )
$SMTPClient.EnableSsl = $true
$SMTPClient.Credentials = New-Object System.Net.NetworkCredential( $emailSmtpUser , $emailSmtpPass );

$SMTPClient.Send( $emailMessage )

来源