Last active
October 31, 2016 22:39
-
-
Save peaeater/04511046e81d17c93b039dbc28cb191b to your computer and use it in GitHub Desktop.
Generates schema and data for a given SQL Server table to file.
This file contains hidden or 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
| <# | |
| Generates a CREATE/INSERT script for a given SQL Server db table (e.g. Localizations) | |
| Peter Tyrrell, Andornot, www.andornot.com | |
| sqlps dependency | |
| If module sqlps does not exist, install from: | |
| Microsoft SQL Server 2016 Feature Pack (https://www.microsoft.com/en-us/download/details.aspx?id=52676) | |
| - SQLSysClrTypes.msi | |
| - SharedManagementObjects.msi | |
| - PowershellTools.msi | |
| #> | |
| param ( | |
| [string]$server = "DATAZOR", | |
| [string]$database = "andi", | |
| [string]$table = "Localizations", | |
| [string]$out = "c:\3_localization-table-with-data.sql" | |
| ) | |
| Push-Location | |
| Import-Module "sqlps" -DisableNameChecking | |
| Pop-Location | |
| <# | |
| MAIN | |
| #> | |
| $srv = New-Object Microsoft.SqlServer.Management.Smo.Server $server | |
| $srv.ConnectionContext.StatementTimeout = 0 | |
| # test server instance is available | |
| try { | |
| $srv.databases | Out-Null | |
| } | |
| catch { | |
| write-host "SQL Server $server not available." -ForegroundColor Red | |
| exit 1 | |
| } | |
| $db = $srv.databases[$database] | |
| # test table is available | |
| try { | |
| $db.Tables[$table] | Out-Null | |
| } | |
| catch { | |
| write-host "$database.$table table not available." -ForegroundColor Red | |
| exit 1 | |
| } | |
| # generate script | |
| write-host "Generating script..." | |
| Push-Location | |
| $scripter = New-Object Microsoft.SqlServer.Management.Smo.Scripter $srv | |
| $scripter.Options.IncludeIfNotExists = $true | |
| $scripter.Options.ScriptSchema = $true | |
| $scripter.Options.ScriptData = $true | |
| $scripter.Options.IncludeHeaders = $true | |
| $scripter.Options.ToFileOnly = $true | |
| $scripter.Options.FileName = $out | |
| $scripter.EnumScript(@($db.Tables[$table])) | |
| Pop-Location | |
| exit 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment