Published on

Exporting Data to CSV using SQL Query and PowerShell

Authors

Problem

Exporting Data to CSV using SQL Query and PowerShell

Solution

$sqlConnection = New-Object System.Data.SqlClient.SqlConnection
$sqlConnection.ConnectionString = "Server=YourServerName;Database=YourDBName;Integrated Security=True"
$sqlConnection.Open()
$sqlCmd = New-Object System.Data.SqlClient.SqlCommand
$sqlCmd.CommandText = "YOUR SQL QUERY HERE"
$sqlCmd.Connection = $sqlConnection
$dataAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$dataAdapter.SelectCommand = $sqlCmd
$dataSet = New-Object System.Data.DataSet
$dataAdapter.Fill($dataSet)
$sqlConnection.Close()
$dataSet.Tables[0] | Export-Csv -Path "C:\Path\To\Your\File.csv" -NoTypeInformation