dbatools is a free PowerShell module with over 300 SQL Server administration, best practice and migration commands included.

Please note that documentation and command names may be out of date while we work furiously towards 1.0


Exports scripts from SQL Management Objects (SMO)



To export all jobs on the SQL Server sql2016 instance using a trusted connection – automatically determines filename as .\sql2016-Job-Export-date.sql

Get-DbaAgentJob -SqlInstance sql2016 | Export-DbaScript

To export only syspolicy_purge_history and ‘Hourly Log Backups’ to C:temp\export.sql and uses the SQL login “sqladmin” to login to sql2016

Get-DbaAgentJob -SqlInstance sql2016 -Jobs syspolicy_purge_history, ‘Hourly Log Backups’ -SqlCredential (Get-Credetnial sqladmin) | Export-DbaScript -Path C:\temp\export.sql

To export jobs and replaces all instances of the servername “sql2014” with “sql2016” then writes to C:\temp\export.sql

Get-DbaAgentJob -SqlInstance sql2014 | Export-DbaJob -Passthru | ForEach-Object { $_.Replace(‘sql2014′,’sql2016’) } | Set-Content -Path C:\temp\export.sql

To export Agent Jobs with the Scripting Options ScriptDrops set to $false and WithDependencies set to true.

$options = New-DbaScriptingOption
$options.ScriptDrops = $false
$options.WithDependencies = $true
Get-DbaAgentJob -SqlInstance sql2016 | Export-DbaScript -ScriptingOptionObject $options


From PowerShell, execute Get-Help Export-DbaScript -Detailed for more information on this function.

Source Code

Want to see the source code? View Export-DbaScript.ps1 on GitHub

Related commands