You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell调用SqlClient DataReader执行查询返回多余连接信息问题

问题原因

这是PowerShell特性和代码笔误共同导致的问题:

  • PowerShell函数的返回值并不仅限于return语句指定的内容:所有没有被赋值给变量、没有被主动丢弃的命令/方法返回值,都会自动加入函数的输出集合,最终一起返回。
  • 你的代码finally块存在笔误:你本来要写$conn.Close()关闭数据库连接,实际写成了$conn.Clone(),Clone()方法会返回一个SqlConnection对象的副本,这个返回值没有被处理,就和你预期返回的查询结果一起作为函数的输出返回。所以你拿到的$updatesForDB实际是包含「SqlConnection对象」和「查询结果字符串」的数组,输出时就会先打印连接对象的全部属性,再打印预期字符串。
修正方案
  1. 修正finally块的笔误,将$conn.Clone()改为$conn.Close(),实现正确的连接关闭逻辑
  2. 对不需要返回值的方法调用统一加[void],避免后续再出现类似的意外输出
  3. 修正调用时的变量名笔误:你定义的连接字符串变量是$conStringCor,调用函数时传的是$connString,二者要保持一致

修正后的完整代码如下:

$conStringCor = "Server=SERVER; Initial Catalog=master;"
$corCred = New-Object System.Data.SqlClient.SqlCredential("user","pwd")

function GetScalarSQL($con_str, $cred, $cmd_text)
{  
    $result = [string]::Empty   
    $conn = New-Object System.Data.SqlClient.SqlConnection($con_str, $cred)   
    try
    {
        $conn.Open()
        $tran = $conn.BeginTransaction()
        $cmd = $conn.CreateCommand()
        $cmd.Transaction = $tran
        $cmd.CommandTimeout = 300
        $cmd.CommandType = [System.Data.CommandType]::Text
        $cmd.CommandText = $cmd_text    
        $dr = $cmd.ExecuteReader()    
        if ($dr.Read())
        {
            $result = ($dr.GetValue(0))
        }
        $dr.Close()
        [void]$dr.Dispose()
        [void]$cmd.Dispose()
        $tran.Commit();
    }
    catch [Exception]
    {
        if($tran -ne $null){      
            $tran.Rollback();
        }
        throw $_.Exception
    }
    finally
    {
        # 修正笔误:Clone改为Close
        $conn.Close()
        [void]$conn.Dispose()
    }

    return $result
}

try
{
    $updatesForDB = [string]::Empty
    # 修正变量名笔误:$connString改为$conStringCor
    $updatesForDB = GetScalarSQL $conStringCor $corCred "select 'this is a test' as [test]"
    Write-Output $updatesForDB
        
}
catch [Exception]
{
    Write-Output $_.Exception.ToString()
    Write-Error $_.Exception.ToString() -EA Stop
}

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 01:06:03