-
-
Save hafei/1de201dbbd94897ddc6fb2bbd726682d to your computer and use it in GitHub Desktop.
powershell script for exporting SQL Server DBs as CSV files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$server = "IE11WIN7\SQLEXPRESS" | |
$tablequery = "SELECT name from sys.tables" | |
$databases = @( | |
"AdjudicationPanel", | |
"Ossc", | |
"Osscahmlr", | |
"ASADJ", | |
"CARESTANDARDS", | |
"CICAP", | |
"WEBEDITORS", | |
"EAT", | |
"ETJR", | |
"Imset", | |
"IT", | |
"Lands", | |
"SENDIST", | |
"Transport", | |
"FVVA", | |
"DCAFE" | |
) | |
foreach ($database in $databases) | |
{ | |
$connectionTemplate = "Data Source={0};Integrated Security=SSPI;Initial Catalog={1};" | |
$connectionString = [string]::Format($connectionTemplate, $server, $database) | |
$connection = New-Object System.Data.SqlClient.SqlConnection | |
$connection.ConnectionString = $connectionString | |
$command = New-Object System.Data.SqlClient.SqlCommand | |
$command.CommandText = $tablequery | |
$command.Connection = $connection | |
#Load up the Tables in a dataset | |
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter | |
$SqlAdapter.SelectCommand = $command | |
$DataSet = New-Object System.Data.DataSet | |
$SqlAdapter.Fill($DataSet) | |
$connection.Close() | |
New-Item -ItemType directory -Path "C:\tribs-export\$($database)" | |
foreach ($Row in $DataSet.Tables[0].Rows) | |
{ | |
$queryData = "SELECT * FROM [$($Row[0])]" | |
#Specify the output location of your dump file | |
$extractFile = "C:\tribs-export\$($database)\$($Row[0]).csv" | |
$command.CommandText = $queryData | |
$command.Connection = $connection | |
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter | |
$SqlAdapter.SelectCommand = $command | |
$DataSet = New-Object System.Data.DataSet | |
$SqlAdapter.Fill($DataSet) | |
$connection.Close() | |
$DataSet.Tables[0] | Export-Csv $extractFile -NoTypeInformation | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
powershell sql server
https://stackoverflow.com/questions/33171372/export-datatable-to-excel-using-powershell
https://github.com/mmessano/PowerShell/blob/master/Export-SQLToExcel-MultiTab.ps1
http://www.sqlserver-dba.com/2013/05/sql-server-export-to-excel-with-powershell.html
https://stackoverflow.com/questions/27917115/powershell-multiple-sql-queries-into-excel-workbook
http://www.maxtblog.com/2014/06/powershell-extracting-sql-server-data-into-excel/