I'm experiencing an issue with a PowerShell function that retrieves data from an database. The function works correctly in PowerShell v7.4 but behaves inconsistently in PowerShell v5.1 when the query returns a single row.
Here is the function:
function Get-Data ($connectstring, $sql) {
# Create a new ODBC Connection
$OLEDBConn = New-Object System.Data.OleDb.OleDbConnection($connectstring)
$OLEDBConn.open()
# Create a new ODBC Command
$readcmd = New-Object system.Data.OleDb.OleDbCommand($sql,$OLEDBConn)
$readcmd.CommandTimeout = '300'
# Create a DataAdapter and fill the DataTable
$da = New-Object system.Data.OleDb.OleDbDataAdapter($readcmd)
$dt = New-Object system.Data.datatable
[void]$da.fill($dt)
$OLEDBConn.close()
return $dt
}
Issue:
- When executing QUERY 1:
$qry= "SELECT * FROM backups" (which returns 3 rows)
$dtres = Get-Data $connString $qry
$dtres.Count
Both PowerShell v5.1 (ISE) and v7.4 (Visual Code) correctly return a count of 3.
- When executing QUERY 2:
$qry= "SELECT 'test'" (which should return 1 row)
$dtres = Get-Data $connString $qry
$dtres.Count
PowerShell v5.1 (ISE) returns $null PowerShell v7.4 (Visual Code) returns 1
- Then, I searched for other properties of the datatable '$dt' and I have found the property '$dt.Rows.Count' (inside the Get-Data function) and it returned the correct number of rows (1) regardless of the PS version.
However, when i tried to get the number of rows using '$dtres.Rows.Count':
$qry= "SELECT 'test'" (which should return 1 row)
$dtres = Get-Data $connString $qry
$dtres.Rows.Count
On both versions the value returned was 0.
Is there a workaround to correctly return the number of rows in PowerShell v5.1 when the query result is a single row?
$dt.Countin 5.1, it's worth noting that$dtresis not a DataTable in either case - PowerShell enumerates the rows of data tables the same way it does arrays or lists. Changereturn $dttoreturn Write-Output $dt -NoEnumerateto fix that (at which point the count issue won't occur anymore)return ,$dt