Just an update: in current versions of SQL Server powershell modules (SQL Server 2014 and on, I believed. Tested on SSMS 17), most of these options are native commands and methods.
For instance, you can use Get-SqlDatabase and methods such as .Script() and .EnumScript(). It's really useful and simple, especially if you want a more granular approach (specific tables and other objects).
For example, this will generate CREATE scripts for user defined functions and save it to file:
$Database = Get-SqlDatabase -ServerInstance $YourSqlServer -Name $YourDatabaseName
$MyFuncs = $Database.UserDefinedFunctions | Where Schema -eq "dbo"
$MyFuncs.Script() | Out-File -FilePath ".\SqlScripts\MyFunctions.sql"
If you want to script data and elements like indexes, keys, triggers, etc. you will have to specify scripting options, like this:
$scriptOptions = New-Object -TypeName Microsoft.SqlServer.Management.Smo.ScriptingOptions
$scriptOptions.NoCollation = $True
$scriptOptions.Indexes = $True
$scriptOptions.Triggers = $True
$scriptOptions.DriAll = $True
$scriptOptions.ScriptData = $True
$Database.Tables.EnumScript($scriptOptions) | Out-File -FilePath ".\AllMyTables.sql"
Note that the Script() method doesn't support scripting data. Use EnumScript() for tables.
A single table:
($Database.Tables | Where Name -eq "MyTableName").EnumScript($scriptOptions)
All your views, save one file per each view, DROP and CREATE script:
ForEach ($view in $($Database.Views | Where Schema -eq "dbo")) {
"`nIF OBJECT_ID('$($view.Name)') IS NOT NULL DROP VIEW $($view.Name);`n`n" | Out-File -FilePath ".\SqlScripts\$($view.Name).sql"
$view.Script() | Out-File -FilePath ".\SqlScripts\$($view.Name).sql" -Append
}
Hope this helps.