Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell PostrgreSQL query returns only fieldcount instead of value

I am trying to get the values of the first twenty rows of column called list_name from the table called mailing_list_membership.

$DBConnectionString = "Driver={PostgreSQL ANSI(x64)};Server=$MyServer;Port=$MyPort;Database=$MyDB;Uid=$MyUid;Pwd=$MyPass;"
$DBConn = New-Object System.Data.Odbc.OdbcConnection;
$DBConn.ConnectionString = $DBConnectionString;
$DBConn.Open();
$DBCmd = $DBConn.CreateCommand();

$DBCmd.CommandText = "SELECT list_name FROM mailing_list_membership LIMIT 20";
$list_name_rows_value  =  $DBCmd.ExecuteReader();

Write-output  $list_name_rows_value 
$DBConn.Close();

However, in powershell for the variable list_name_rows_value it only returns the field count.

FieldCount
----------
     1
     1
     1
     1
     1
     1
     1
     1
     1
     1
     1
     1
     1
     1
     1
     1
     1
     1
     1
like image 630
user6927085 Avatar asked Sep 07 '25 18:09

user6927085


1 Answers

With SqlDataReader objects you need to traverse the result set yourself, e.g. like this:

$rdr = $DBCmd.ExecuteReader()
while ($rdr.Read()) {
  $rdr.GetValue(0)
}

It's more convenient to have the reader fill a datatable that you can display using the regular Format-* cmdlets:

$rdr = $DBCmd.ExecuteReader()
$tbl = New-Object Data.DataTable
$tbl.Load($rdr)
$rdr.Close()

$tbl | Format-Table -AutoSize
like image 114
Ansgar Wiechers Avatar answered Sep 09 '25 23:09

Ansgar Wiechers