PowerShell将$ null转换为0

时间:2014-09-24 21:15:08

标签: powershell type-conversion powershell-v2.0

我有一个非常简单的函数来获取SQL结果:

function RunSqlCommand($sql)
{
    $connection = $null
    $command = $null
    try
    {
        $connectionString = "data source=localhost; integrated security=true"
        $connection = New-Object System.Data.SqlClient.SqlConnection($connectionString)
        $command = $connection.CreateCommand()
        $command.CommandText = $sql
        $adapter = New-Object System.Data.SqlClient.SqlDataAdapter($command)
        $dataSet = New-Object System.Data.DataSet
        $adapter.Fill($dataSet)
        $results = $dataSet.Tables | Select-Object -ExpandProperty "Rows"
        return $results
    }
    finally
    {
        if ($command -ne $null) { $command.Dispose() }
        if ($connection -ne $null) { $connection.Dispose() }
    }
}

每当没有结果时,$results变量为$null。但是,当我检查调用方法中的返回值时,它神奇地变为0

PowerShell在幕后做些什么吗?我确实想要返回$null来表示“没有结果”。

1 个答案:

答案 0 :(得分:1)

$adapter.Fill()返回数据集中添加或刷新的行数。

要修复,您可以这样做:

[void]$adapter.Fill($dataSet)

$adapter.Fill($dataset) | out-null