Oracle查询并输出到CSV

时间:2017-03-08 16:33:25

标签: oracle powershell

我想寻求有关如何使用oracle查询的相同宽格式输出将oracle查询输出到csv的建议。 以下是我的代码

的摘录
[System.Reflection.Assembly]::LoadWithPartialName("System.Data.OracleClient") | Out-Null 
$connection = New-Object System.Data.OracleClient.OracleConnection($connectionString) 
$command = new-Object System.Data.OracleClient.OracleCommand($queryString, $connection) 
$connection.Open() 
$users = $command.ExecuteReader() 
$Counter = $users.FieldCount 

$dataset = 
  @(  while ($users.Read()) { 
         for ($i = 0; $i -lt $Counter; $i++) { 
       New-Object PsObject -Property @{ Key = $users.GetName($i)
                                       Value = $users.GetValue($i)
                                     }
                                     }
    }) 
$connection.Close() 

输出:

PS C:\WINDOWS\system32> $dataset

Key             Value          
---             -----          
PRCDNAME        A123rw-T03 
ASSY_PART1      wrwrwee-A03  
ASSY_PART2      wrewrwe-A0CAD
ASSY_PART3      wer         
ASSY_PART4                     
ASSY_PART5                     
ASSY_PART6                     
OUTPN_1         rgsrggs-3     
OUTPN_2                        
OUTPN_3                        
OUTPN_4                        
OUTPN_5                        
OUTPN_6                        
OUTPN_7                        
OUTPN_1_ALLOC1 

我想将其格式化如下。基本上我需要Key列作为标题

PRCDNAME,ASSY_PART1,ASSY_PART2 ,......,

A123rw-T03,wrwrwee-A03,wrewrwe-A0CAD,....,    

1 个答案:

答案 0 :(得分:1)

从对象列表中创建一个哈希表:

$ht = @{}
$dataset | ForEach-Object { $ht[$_.Key] = $_.Value }

然后从该哈希表中创建一个对象并将其导出为CSV:

New-Object -Type PSObject -Property $ht | Export-Csv 'C:\path\to\output.csv' -NoType