PowerShell正在将$null转换为0
我有一个非常直接的函数来获取SQL结果:PowerShell正在将$null转换为0,powershell,type-conversion,powershell-2.0,Powershell,Type Conversion,Powershell 2.0,我有一个非常直接的函数来获取SQL结果: function RunSqlCommand($sql) { $connection = $null $command = $null try { $connectionString = "data source=localhost; integrated security=true" $connection = New-Object System.Data.SqlClient.SqlCon
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
以表示“无结果”。$adapter.Fill()
返回在数据集中添加或刷新的行数
要修复此问题,您可以执行以下操作:
[void]$adapter.Fill($dataSet)
或
所以,即使我显式地返回一个值,powershell也会返回其他值?当有行要返回时,为什么不获取0?找到了一个很好的解释此行为的博客:这是PowerShell的独特行为,任何“未捕获”的值都会添加到输出流中。
$adapter.Fill($dataset) | out-null