【问题标题】:getting Exception while calling function调用函数时出现异常
【发布时间】:2020-08-20 20:37:38
【问题描述】:

如果我调用函数,我会遇到异常

我在for循环中使用了返回值

2020-08-19T09:25:31.6470906Z row count:: 1
2020-08-19T09:25:31.6495736Z row count:: trns 1 System.Data.DataRow
2020-08-19T09:25:31.7884278Z ##[error]Cannot compare "System.Data.DataRow" because it is not IComparable.
2020-08-19T09:25:33.4007345Z ##[error]PowerShell exited with code '1'.
function getResultlist($sqlquery ){

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection 
$SqlConnection.ConnectionString = "Server = $sqlserver; Database = $sqldatabasename; User ID = $sqlusername; Password = $sqlpassword; Connection Timeout=0"
$sqlConnection.Open()
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $sqlquery
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter 
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()
$rowCount = $DataSet.Tables[0].Rows.Count
Write-Host "row count::" $rowCount
return $DataSet.Tables[0].Rows

我使用的这个功能如下。我正在将此函数结果转换为变量并在 for 循环中使用

$rowCountTrn = getResultlist($testQuery)
Write-Host "row count:: trns" $rowCountTrn

if ($rowCountTrn -gt 0) {
    $mailtabData = $null
    
    foreach ($row in  $rowCountTrn ) {
        
            $mailtabData += "<tr><td>" + $row[0] + "</td><td>" + $row[1] + "</td><td>" + $row[2] + "</td></tr>"
            $sendemail = $true
        }
    }

【问题讨论】:

  • 异常信息是什么?请粘贴完整的错误消息。
  • 当你得到错误时,你能显示你用来调用/执行函数的代码吗?

标签: powershell


【解决方案1】:

错误是由于以下语句引起的:

if($rowCountTrn -gt 0){

当 PowerShell 看到-gt 比较运算符时,它必须想办法比较这两个值。左侧操作数$rowCountTrnDataRow 对象的数组,而DataRow 不是 可比较的类型(它没有实现IComparable interface),所以表达式因您看到的错误而失败。

如果要确保至少返回一个数据行,请使用Count

if($rowCountTrn.Count -gt 0){

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多