Oracle Sql and Powershell : Execute query, print/output results

时间:2016-04-15 14:52:19

标签: sql oracle powershell

I need a way to execute a SQL (by importing a .SQL script) on a remote Oracle DB using PowerShell. In addition to this I am also trying to output the results in an .xls format in a desired folder location. To add to the fun, I would also want to run this task on an automatic schedule. Please help !

I have gotten so far :

[System.Reflection.Assembly]::LoadWithPartialName ("System.Data.OracleClient") | Out-Null
$connection = "my TNS entry"
$queryString = "my SQL query"    
$command = new-Object System.Data.OracleClient.OracleCommand($queryString, $connection) 
$connection.Open()
$reader = $command.ExecuteReader()
$tempArr = @()
#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
    $tempArr+= new-object psobject -property $row
  }
$connection.Close()
write-host "Conn State--> " $connection.State
$tmpArr | Export-Csv "my File Path" -NoTypeInformation
$Error[0] | fl -Force 

1 个答案:

答案 0 :(得分:0)

最简单的方法是通过powershell驱动sqlplus.exe。要执行sql并获取输出,请执行以下操作:

 $result = sqlplus.exe @file.sql [credentials/server] 
 #parse result into CSV here which can be loaded into excel

您可以使用以下内容安排此脚本:

 schtasks.exe /create /TN sqlplus /TR "Powershell -File script.ps1" /ST 10 ...

为此你需要安装sqlplus(它附带oracle express,你可以在没有它的情况下安装它)。这显然引入了不需要的依赖,但sqlplus可用于检查数据库并做任何可能是好事的东西。