PowerShell and SQL Server – Exporting Data (CSV)

Sometimes it can be useful to export data from a database, so that it can be analysed, or, to import in to another computer system. CSV, or Comma Separated Value files, are one such file format that allows for both of these scenarios.

The example below exports data from a table called ‘person’, which contains five columns, ‘id’, ‘firstname’, ‘lastname’, ‘title’ and ‘dob’, from within an SQL Server database, to a CSV file in a specified location.

id firstname lastname title dob
1 Bob Smith Mr 1980-01-20
3 Fred Bloggs Mr 1975-05-07
4 Alan White Mr 1989-03-20
5 Fiona Bloggs Mrs 1985-05-19
6 Zoe Davis Miss 1979-07-11
7 Tom Ingram Mr 1971-10-04
8 Karen Thomas Mrs 1969-03-08
9 Samantha Yates Miss 1995-08-27

Firstly, variables are defined to facilitate the connection and authentication to the database. This is followed by a query string to extract, or select, the data from the ‘person’ table, as well as variables for the CSV file path and name. If the file path exists, the ‘Invoke-Sqlcmd’ and ‘Export-Csv’ cmdlets are used to connect to the database using the specified variables, extract the data using the query string and export it in CSV format to the desired location. Feedback is provided as to the success or failure of the task.

# Clear the console window.

# Database variables.
$server = "localhost\MSSQLSERVERDEMO"
$database = "Demo"
$username = "DemoUN"
$password = "DemoPW"

# SQL query to select all data in the person table.
$query = "SELECT * FROM [dbo].[person] ORDER BY [id]"

# Export path and file.
$exportPath = "C:\Demo\"
$exportCsv = "personexport.csv"

# Check to see if the file path exists.
if (Test-Path $exportPath)


        # Extract the data and export to CSV.
        Invoke-Sqlcmd -ServerInstance $server -Database $database `
        -Username $username -Password $password -Query $query -ErrorAction Stop `
        | Export-Csv -Path $exportPath$exportCsv -Delimiter "," -NoTypeInformation

        # Message stating export successful.
        Write-Host "Data export successful"


        # Message stating export unsuccessful.
        Write-Host "Data export unsuccessful."



    # Message stating file path does not exist.
    Write-Host "File path does not exist."


The CSV file produced contains the following data. Note that, although dates in an SQL Server database are stored in the format YYYY-MM-DD (four digit year, two digit month and two digit day), they are output to CSV in a day, month, year and time format.

"1","Bob","Smith","Mr","20/01/1980 00:00:00"
"3","Fred","Bloggs","Mr","07/05/1975 00:00:00"
"4","Alan","White","Mr","20/03/1989 00:00:00"
"5","Fiona","Bloggs","Mrs","19/05/1985 00:00:00"
"6","Zoe","Davis","Miss","11/07/1979 00:00:00"
"7","Tom","Ingram","Mr","04/10/1971 00:00:00"
"8","Karen","Thomas","Mrs","08/03/1969 00:00:00"
"9","Samantha","Yates","Miss","27/08/1995 00:00:00"