Connect to SQL Database and Output data to CSV File from Table using Powershell

This is sample Powershell code for connecting to SQL Database and outputting table data to a CSV file.

Code below was tested by me.

Reference: 
https://stackoverflow.com/questions/25682703/connect-to-sql-server-database-from-powershell

Powershell Code to Connect to SQL Server & Output to CSV File

$SQLServer = "aaaa.database.windows.net"
$SQLDBName = "Database"
$uid ="john"
$pwd = "pwd123"
$SqlQuery = "SELECT * from table;"
$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = $SQLServer; Database = $SQLDBName; Integrated Security = True; User ID = $uid; Password = $pwd;"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlQuery
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)

$DataSet.Tables[0] | out-file "C:\Scripts\xxxx.csv"

Author: Rick Cable / AKA Cyber Abyss

A 16 year US Navy Veteran with 25+ years experience in various IT Roles in the US Navy, Startups and Healthcare. Founder of FinditClassifieds.com in 1997 to present and co-founder of Sports Card Collector Software startup, LK2 Software 1999-2002. For last 7 years working as a full-stack developer supporting multiple agile teams and products in a large healthcare organization. Part-time Cyber Researcher, Aspiring Hacker, Lock Picker and OSINT enthusiast.

Leave a Reply