【问题标题】:Database query output to CSV数据库查询输出到 CSV
【发布时间】:2015-08-11 17:05:07
【问题描述】:

下面是我的 PowerShell 代码,它运行良好。

[Reflection.Assembly]::LoadFile("E:\oracle\product\11.2.0\ODP.NET\bin\2.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 屏幕或输出中以表格格式显示它?

【问题讨论】:

    标签: oracle powershell powershell-2.0 export-to-csv


    【解决方案1】:

    我过去做过类似的事情,我没有将它导出为 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
    

    【讨论】:

    • 感谢您的回答。我明天试试,让你知道。投票赞成
    【解决方案2】:

    从每条记录的字段构建自定义对象,然后将对象列表导出到 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
    

    【讨论】:

    • 你确定吗,因为大部分事情我都想不通。
    • @404 我无法对此进行测试,因为我无法访问 Oracle 数据库,但我希望它能够工作。该方法与 Dane Boulton 建议的方法几乎相同,只是它避免在循环中附加到数组。
    猜你喜欢
    • 2018-04-16
    • 2011-07-22
    • 2022-12-11
    • 2020-08-03
    • 2015-02-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多