Created
April 7, 2015 19:21
-
-
Save johnmmoss/1531cd82b9a592aca9d5 to your computer and use it in GitHub Desktop.
PowerShell SQL script table
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
# The file that the script is written to | |
$file = "C:\scripts\ps\department.sql" | |
# declare variables and create path | |
$server = "localhost"; | |
$instance = "default"; | |
$database = "timesheet"; | |
$path = "sqlserver:\sql\$server\$instance\databases\$database\tables" ; | |
# filter down to a particular table | |
$tableName = "department"; | |
$tableset = get-childitem $path -ErrorAction stop | where-object {$_.name -eq $tableName} ; | |
$options = New-Object Microsoft.SqlServer.Management.Smo.ScriptingOptions ($srv); | |
$options.DriAllConstraints = $TRUE; | |
# We have filtered to a specified table, now script it | |
$script = $tableset[0].script($options); | |
#output the table to $file and console | |
write-host $script | |
$script | out-file $file -append -ErrorAction stop | |
"GO" | out-file $file -append |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment