Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell script export SQL to CSV add delimiter

Tags:

powershell

I'm doing a script to export data from a SQL Server database. I want to output a .csv file with as delimiter ";".

Here is my script:

#Variable to hold variable  
$SQLServer = "SERVEUR"  
$SQLDBName = "TOTO"  
$uid ="PS"  
$pwd = "password123"   
$delimiter = ";"

#SQL Query  
$SqlQuery = "SELECT * from $SQLDBName.dbo.SAGE_TO_PRESTASHOP;"  
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection  
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True;"  
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand  
$SqlCmd.CommandText = $SqlQuery  
$SqlCmd.Connection = $SqlConnection  
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter  
$SqlAdapter.SelectCommand = $SqlCmd   
#Creating Dataset  
$DataSet = New-Object System.Data.DataSet  
$SqlAdapter.Fill($DataSet)  
$DataSet.Tables[0] | Out-File "E:\EXPORTS\export.csv"  
like image 489
Chris99391 Avatar asked Dec 12 '18 11:12

Chris99391


People also ask

What is NoTypeInformation in PowerShell?

The NoTypeInformation parameter removes the #TYPE information header from the CSV output and is not required in PowerShell 6. The output shows that the file is not written because access is denied. The Force parameter is added to the Export-Csv cmdlet to force the export to write to the file.

How do I add data to a CSV file in PowerShell?

To simply append to a file in powershell,you can use add-content. So, to only add a new line to the file, try the following, where $YourNewDate and $YourDescription contain the desired values.


1 Answers

Replace your bottom line with this:

$DataSet.Tables[0] | export-csv -Delimiter $delimiter -Path "E:\EXPORTS\export.csv" -NoTypeInformation 
like image 152
Eric Weintraub Avatar answered Sep 24 '22 11:09

Eric Weintraub