Powershell PostrgreSQL 查询仅返回字段计数而不是值

use*_*085 4 postgresql powershell

我试图从名为 mailing_list_membership 的表中获取名为 list_name 的列的前二十行的值。

$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();
Run Code Online (Sandbox Code Playgroud)

但是,在 powershell 中,对于变量 list_name_rows_value,它仅返回字段计数。

FieldCount
----------
     1
     1
     1
     1
     1
     1
     1
     1
     1
     1
     1
     1
     1
     1
     1
     1
     1
     1
     1
Run Code Online (Sandbox Code Playgroud)

Ans*_*ers 5

对于SqlDataReader对象,您需要自己遍历结果集,例如:

$rdr = $DBCmd.ExecuteReader()
while ($rdr.Read()) {
  $rdr.GetValue(0)
}
Run Code Online (Sandbox Code Playgroud)

让读者填写可以使用常规Format-*cmdlet 显示的数据表会更方便:

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

$tbl | Format-Table -AutoSize
Run Code Online (Sandbox Code Playgroud)