Skip to content

Instantly share code, notes, and snippets.

@NReilingh
Created February 9, 2018 17:16
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save NReilingh/813400c9a39bba41ca56d4bd9e0e3948 to your computer and use it in GitHub Desktop.
Save NReilingh/813400c9a39bba41ca56d4bd9e0e3948 to your computer and use it in GitHub Desktop.
Using SQL SMO in PowerShell to script SQL Server objects
Add-Type -Path 'C:\Program Files\Microsoft SQL Server\140\SDK\Assemblies\Microsoft.SqlServer.Smo.dll'
$SmoServer = New-Object ('Microsoft.SqlServer.Management.Smo.Server') -argumentlist 'localhost'
$SmoServer.ConnectionContext.LoginSecure = $false
$SmoServer.ConnectionContext.set_Login("sa")
$SmoServer.ConnectionContext.set_Password("Passw0rd!")
$db = $SmoServer.Databases['msdb']
$Objects = $db.Tables
$Objects += $db.Views
$Objects += $db.StoredProcedures
$Objects += $db.UserDefinedFunctions
# Progress tracking
[int]$TotObj = $Objects.Count
[int]$CurObj = 1
# Build this portion of the directory structure out here in case scripting takes more than one minute.
$SavePath = "C:\TEMP\DbFiles\$(Get-Date -Format yyyyMMddHHmm)"
foreach ($CurrentObject in $Objects) {
$TypeFolder = $CurrentObject.GetType().Name
$OutputFile = "$($CurrentObject.Name).sql"
$OutputFolder = "$SavePath\$TypeFolder"
if (!(Test-Path -Path $OutputFolder)) {
New-Item -ItemType directory -Path $OutputFolder
}
# Create a Scripter object with our preferences.
$Scripter = New-Object ('Microsoft.SqlServer.Management.Smo.Scripter') ($SmoServer)
$Scripter.Options.FileName = "$OutputFolder\$OutputFile"
$Scripter.Options.AppendToFile = $True
$Scripter.Options.AllowSystemObjects = $False
$Scripter.Options.ClusteredIndexes = $True
$Scripter.Options.DriAll = $True
$Scripter.Options.ScriptDrops = $False
$Scripter.Options.IncludeHeaders = $False
$Scripter.Options.ToFileOnly = $True
$Scripter.Options.Indexes = $True
$Scripter.Options.Permissions = $True
$Scripter.Options.WithDependencies = $False
$Scripter.Options.Encoding = [System.Text.Encoding]::ASCII
# This is where each object actually gets scripted one at a time.
Write-Output "[$CurObj of $TotObj] ($("{0:P1}" -f ($CurObj / $TotObj))) Scripting out $TypeFolder $CurrentObject"
$Scripter.Script($CurrentObject)
$CurObj++
} # This ends the loop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment