1
在PowerShell中,我试图触发一个电子邮件发送,只有当有一个SQL查询的结果。电子邮件功能和数据库连接工作正常,但基于SQL结果的“if then”语句不起作用 - 我不认为$ result = [bool]是有效的。Powershell - 如果SQL查询返回一个结果,然后运行功能
如果从SQL语句返回任何记录,并且电子邮件将包含SQL结果,最终结果将是仅发送的电子邮件。
这是我到目前为止有:
$result = [bool]("
SELECT *
FROM table
WHERE condition")
If ($result -eq $true) {
function Invoke-SQL ($dataset) {
$connectionString = "server=servername;uid=valuehere;pwd=passwordhere;database=dbnamehere;"
$sqlCommand = "
SELECT *
FROM table
WHERE condition"
"
$connection = new-object system.data.SqlClient.SQLConnection($connectionString)
$command = new-object system.data.sqlclient.sqlcommand($sqlCommand,$connection)
$connection.Open()
$adapter = New-Object System.Data.sqlclient.sqlDataAdapter $command
$adapter.Fill($dataSet) #| Out-Null
$connection.Close()
}
function Invoke-Email ($dataset) {
foreach ($Row in $dataset.Tables[0].Rows)
{
write-host "value is : $($Row[0])"
}
$From = "email"
$To = "email"
$Subject = "subject here"
$Body = echo 'email body here' $dataset.tables[ 0 ] | Out-String
$SMTPServer = "server here"
Send-MailMessage -From $From -to $To -Subject $Subject -Body $Body -SmtpServer $SMTPServer
#-Port $Port
}
$dataset = New-Object System.Data.DataSet
Invoke-SQL $dataset
$dataset.Tables
Invoke-Email $dataset
$result
请注意,这只适用于返回行的语句。 – emanresu