Created
April 8, 2015 07:02
-
-
Save johnmmoss/589627f0a81b48bd8c4e to your computer and use it in GitHub Desktop.
PowerShell Script SQL table create statements
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
# declare variables and create path | |
$server = "localhost"; | |
$instance = "default"; | |
$database = "timesheet"; | |
$path = "sqlserver:\sql\$server\$instance\databases\$database\tables" ; | |
# We still have a filter, kind of.. | |
$tables = "*"; | |
# The output directory for our scripts | |
$outputdir= "C:\SCRIPTS"; | |
# Do a bit more with the options | |
$tableset = get-childitem $path -ErrorAction stop | where-object {$_.displayname -like $tables} ; | |
$options = New-Object Microsoft.SqlServer.Management.Smo.ScriptingOptions ($srv); | |
$options.NoCollation = $TRUE; | |
$options.DriPrimaryKey = $TRUE; | |
$options.DriAllConstraints = $TRUE; | |
# We do some tidying up using regexs | |
$regex1 = "SET[\s\w]*ON"; # remove the SET statments from the top | |
$regex2 = "WITH\s\(PAD_INDEX[\w\s\)\(\[\]=,]*ON\s\[PRIMARY\]"; # remove the defaults from PK | |
$regex3 = "ALTER TABLE\s[\.\w\[\]]*\sCHECK\sCONSTRAINT\s\[\w+\]"; # remove ALTER TABLE ... CHECK CONSTRAINT COMMANDS | |
$script = ""; | |
$outputfilepath = ""; | |
# Remove Current Files | |
Remove-Item $outputdir\*.sql | |
# script each table | |
write-host "Writing files:" | |
foreach ($table in $tableset) | |
{ | |
$outputfilepath = $outputdir + "\" + $table.name + ".sql" | |
write-host $outputfilepath | |
$script = $table.script($options); | |
# Split the ALTER TABLE statments to a new line. | |
$script = [regex]::replace($script, "ALTER TABLE", " | |
ALTER TABLE"); | |
# Remove the set options | |
$script = [regex]::replace($script, $regex1, ""); | |
# Remove the unwanted PK settings and replace with required FK build token | |
$script = [regex]::replace($script, $regex2, ") | |
-- FOREIGN KEY CONSTRAINTS"); | |
# Next we remove ALTER TABLE ... CHECK CONSTRAINT commands. | |
$script = [regex]::replace($script, $regex3, ""); | |
$script | out-file $outputfilepath; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment