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.

A rolling seven day backup is also included. This makes a copy of the CSV file that has just been created, giving it a name that includes the index number for the day of the week, along with the day itself, for example, 'personexport-1-monday.csv', for the backup on a Monday. Here, Sunday is classed as the first day of the week, with an index value of zero. Note that the backup is only done for the first time that this is run in a given day. Backups are then overwritten each week.

Feedback is provided as to the success or failure of the task.

# Clear the console window.
Clear-Host

# Database variables.
$server = "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)
{

    try
    {

        # 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

        # Today's date.
        $today = Get-Date

        # Construct the backup file name.
        $exportBackupCsv = $exportCsv.Substring(0, $exportCsv.Length-4) + "-" + `
                           [int]$today.DayOfWeek + "-" + `
                           $today.DayOfWeek.ToString().ToLower() + ".csv"

        # Check if the backup file does not exist, or if it does, check that
        # today's date is different from the last modified date.
        if (-not (Test-Path ($exportPath + $exportBackupCsv)) -or `
           ((Test-Path ($exportPath + $exportBackupCsv)) -and `
            ((Get-Item ($exportPath + $exportBackupCsv)).LastWriteTime.date -ne $today.Date)))
        {

            # Copy the CSV export.
            Copy-Item ($exportPath + $exportCsv) `
            -Destination ($exportPath + $exportBackupCsv) -Force

        }

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

    }
    catch
    {

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

    }

}
else
{

    # 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.

"id","firstname","lastname","title","dob"
"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"