Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Powershell to save a datatable as a csv

There has to be an easy way to do this. I have a Powershell script which connects to a database and I want to save the resulting datatable as a CSV. Here is the code so far:

$connString = "Provider=msdaora;Data Source=MyDatabase;User Id=test;Password=test    
$qry = "select * from employees"
$OLEDBConn = New-Object System.Data.OleDb.OleDbConnection($connString)            
$OLEDBConn.open()            
$readcmd = New-Object system.Data.OleDb.OleDbCommand
$readcmd.Connection = $OLEDBConn
$readcmd.CommandTimeout = '300'
$readcmd.CommandText = $qry
$da = New-Object system.Data.OleDb.OleDbDataAdapter($readcmd)            
$dt = New-Object system.Data.datatable            
[void]$da.fill($dt)            
$OLEDBConn.close()
like image 835
Matthew Crews Avatar asked Apr 14 '12 00:04

Matthew Crews


1 Answers

this should do it I think:

$ds = New-Object System.Data.DataSet
$da.Fill($ds) >$null| Out-Null
$ds.Tables[0] | export-csv tofile.csv -notypeinformation
like image 69
Adam Seabridge Avatar answered Oct 25 '22 01:10

Adam Seabridge