数据库查询输出到 CSV

Database query output to CSV

下面是我的 PowerShell 代码,它工作正常。

[Reflection.Assembly]::LoadFile("E:\oracle\product.2.0\ODP.NET\bin.x\Oracle.DataAccess.dll")

$constr = "User Id=system;Password=pass;Data Source=API"
$conn= New-Object Oracle.DataAccess.Client.OracleConnection($constr)
$conn.Open()
$sql="select * from dba_users"
$command = New-Object Oracle.DataAccess.Client.OracleCommand($sql,$conn)
$reader=$command.ExecuteReader()

while($reader.Read()){
  $reader.GetString(0)
}

$conn.Close()

问题是我想将结果导出到 CSV。如何在 PowerShell 中执行此操作?另外,如何在 PowerShell 屏幕或输出中以表格格式显示它?

我过去做过类似的事情,我没有将它报告为 csv,但它应该可以工作。

$someArray = @()
    #read all rows into a hash table
    while ($reader.Read())
    {
        $row = @{}
        for ($i = 0; $i -lt $reader.FieldCount; $i++)
        {
            $row[$reader.GetName($i)] = $reader.GetValue($i)
        }
        #convert hashtable into an array of PSObjects
        $someArray += new-object psobject -property $row            
    }
$conn.Close()
$someArray | export-csv C:\temp\someFile.csv

从每条记录的字段构建自定义对象,然后将对象列表导出到 CSV:

$colNames = $reader.GetSchemaTable() | select -Expand ColumnName

$data = while ($reader.Read()) {
  $obj = New-Object -Type PSCustomObject

  for ($i = 0; $i -lt $colNames.Count; $i++) {
    $obj | Add-Member -Type NoteProperty -Name $colNames[$i] -Value $reader.GetString($i)
  }

  $obj
}

$data | Export-Csv 'C:\path\to\output.csv' -NoType

代码取自 here(大约在页面的中间位置,但您可能需要完整阅读文章)。

将数据通过管道传输到 Format-Table 以在 PowerShell 控制台中获得表格输出:

$data | Format-Table -AutoSize