Skip to content

Instantly share code, notes, and snippets.

@johnmmoss
Created April 7, 2015 19:21
Show Gist options
  • Save johnmmoss/1531cd82b9a592aca9d5 to your computer and use it in GitHub Desktop.
Save johnmmoss/1531cd82b9a592aca9d5 to your computer and use it in GitHub Desktop.
PowerShell SQL script table
# 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