Powershell - 如果 SQL 查询 returns 结果,则 运行 函数

Powershell - If SQL query returns a result, then run function

在 PowerShell 中,我试图触发仅当 SQL 查询有任何结果时才发送电子邮件。电子邮件功能和数据库连接工作正常,但基于 SQL 结果的 "if then" 语句不起作用 - 我认为 $result = [bool] 无效。

最终结果将是仅当 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

根据您当前执行查询的方法,您至少可以做两件事来完成此操作。对于使用 dataAdapter 的 'fill' 方法执行的简单 SELECT 查询, return 值应该是查询编辑的行数 return。你可以这样做:

$resultCount = $adapter.fill($dataSet)

然后检查 $resultCount 是否大于 0。

if($resultCount -gt 0){
   #invoke your email function here
}

您也可以像这样检查数据的行数 table:

$dataSet.Tables[your table name or index].Rows.Count

再次简单地检查是否大于 0。

if($dataSet.Tables[your table name or index].Rows.Count -gt 0){
    #invoke your email function here
}

我推荐第二种计算数据行数的方法table,因为您不必担心可用的不同数据适配器对象的差异。