Reputation: 8695
I have a pretty straight-forward function for grabbing SQL results:
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() }
}
}
Whenever there are no results, the $results
variable is $null
. However, when I inspect the return value in the calling method, it magically becomes 0
.
Is PowerShell doing something behind the scenes? I really do want to return $null
to represent "no results".
Upvotes: 0
Views: 694
Reputation: 18146
$adapter.Fill()
returns the number of rows added or refreshed in the dataset.
To fix, you can do this:
[void]$adapter.Fill($dataSet)
or
$adapter.Fill($dataset) | out-null
Upvotes: 1