Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Exports table data and headers as CSV file
if ($args.Count -le 2)
throw "Usage: <server name> <db name> <script file>"
$servername = $args[0]
$database = $args[1]
$sourcefile = $args[2]
[system.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | out-null
$server = New-Object ("Microsoft.SqlServer.Management.SMO.Server") ($servername)
$1 = Get-Item($sourcefile)
$ds = $server.Databases[$database].ExecuteWithResults("$(Echo $1.OpenText().ReadToEnd())")
$cnt = 0
Foreach ($dt in $ds.Tables)
$cnt ++
Write-Host "Writing table: "$cnt
$file = ".\" + $cnt.ToString() + ".csv"
$dt | export-csv $file -notypeinformation
Write-Host "Completed!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.