Feb 12, 2013
Script SQL Server Agent Jobs Using PowerShell
It’s that time of the month again, no not that one, it’s T-SQL Tuesday time and this weeks topic is hosted by Wayne Sheffield (blog|twitter).
If you don’t know what T-SQL Tuesday is, you’re either new to the SQL community or have had your head buried in the sand. I’m not going to repeat what others have said a thousand times over, as much as I do love the sound of my own voice, but essentially it’s a cracking excuse for SQL folk to Blog and discuss a common topic. If you’re a member of the Twitterverse you can follow the discussion online using the #TSQL2sDay hash tag.
This months theme is “blog about using PowerShell for doing, well, anything as long as it is related to SQL Server or the computer that SQL Server runs on”.
I’m currently busy breaking our Production environment and so rather than miss this months theme I’m re-sharing a previous post (in case you’re wondering about comment dates etc.) .
Script SQL Server Agent Jobs Using PowerShell
As many of you already know, I’m a big fan of Automating Everything and so I’ve been learning to use PowerShell with SQL Server.
Interested to know what other DBAs are using PowerShell for, I reached out to the Twitterverse for insight.
@JohnSansom I use #powershell for #configuration purposes and quick #inventory of sqlserver stuff (settings, statistics, DMV queries, …)
— Johan Bijnens (@alzdba) February 27, 2012
@JohnSansom all sorts
monitoring, data collection, general windows admin (AD stuff adding users computers etc), installs, etc…
— James Boother (@JimmyBoo) February 27, 2012
Clearly there are a lot of clever folks out there already taking advantage of PowerShell to administer SQL Server.
I think that I have now got to a point in my own learning where I’m dangerous enough with PowerShell for it to be worth sharing some of this knowledge with you. I recently had a need to script out all SQL Server Agent Jobs for a large number of instances. Deflated by the thought of having to do so manually, I instead chose to turn to some PowerShell magic in order to accomplish the task. Below you will find the PowerShell script to achieve this.
PowerShell Code to Script Out All SQL Server Agent Jobs
# Date: 23/02/12
# Author: John Sansom
# Description: PS script to generate all SQL Server Agent jobs on the given instance.
# The script accepts an input file of server names.
# Version: 1.0
#
# Example Execution: .\Create_SQLAentJobSripts.ps1 .\ServerNameList.txt
param([String]$ServerListPath)
#Load the input file into an Object array
$ServerNameList = get-content -path $ServerListPath
#Load the SQL Server SMO Assemly
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo") | Out-Null
#Create a new SqlConnection object
$objSQLConnection = New-Object System.Data.SqlClient.SqlConnection
#For each server in the array do the following..
foreach($ServerName in $ServerNameList)
{
Try
{
$objSQLConnection.ConnectionString = "Server=$ServerName;Integrated Security=SSPI;"
Write-Host "Trying to connect to SQL Server instance on $ServerName..." -NoNewline
$objSQLConnection.Open() | Out-Null
Write-Host "Success."
$objSQLConnection.Close()
}
Catch
{
Write-Host -BackgroundColor Red -ForegroundColor White "Fail"
$errText = $Error[0].ToString()
if ($errText.Contains("network-related"))
{Write-Host "Connection Error. Check server name, port, firewall."}
Write-Host $errText
continue
}
#IF the output folder does not exist then create it
$OutputFolder = ".\$ServerName"
$DoesFolderExist = Test-Path $OutputFolder
$null = if (!$DoesFolderExist){MKDIR "$OutputFolder"}
#Create a new SMO instance for this $ServerName
$srv = New-Object "Microsoft.SqlServer.Management.Smo.Server" $ServerName
#Script out each SQL Server Agent Job for the server
$srv.JobServer.Jobs | foreach {$_.Script()} | out-file ".\$OutputFolder\jobs.sql"
}
If you would you like to read more posts on PowerShell let me know.











Mar 01, 2012 @ 15:52:00
Thanks for putting this out there. I wanted to do something similar and was able to use your script and get everything scripted out in about 5 minutes. I guess I can go home now.
Mar 01, 2012 @ 16:57:00
Great work Mike! Working smarter not harder in action there. It’s part of the PowerShell magic.
I don’t know about clocking off early for the day but I would say you’ve certainly earned yourself a beer.
Thanks for your comments sir.
Mar 01, 2012 @ 22:09:00
Hey John,
Another enlightening article once again mate. Good stuff!Powershell is something we are seriously underutilising in our shop. Do you have any useful links to hand where I can start learning and produce magic with?
Mar 02, 2012 @ 08:21:00
Hey Samuel, thanks. I’m glad you enjoyed it.
It’s interesting because right now I don’t actually have a favourite go to resource for PowerShell. Instead I seem to encounter snippets of useful content and knowledge spread across various online sources. I am however currently reading the book “Learn Windows PowerShell in a Month of Lunches” which I’m particularly enjoying.
Sounds like I should be putting together a list of PowerShell resources on the blog. As you discover resources that you find particularly good do let me know!
Thanks for your comments!
Mar 08, 2012 @ 14:18:00
Your custom script works beautifully. Just tested on multiple SQL Servers.
Thanks for sharing!
Mar 08, 2012 @ 14:28:00
My pleasure sir. Thanks for your comment.
Mar 08, 2012 @ 21:54:00
Here’s a small modification of your code to allow it to script out each job to a separate file, and deal with non-windows characters.
Mar 09, 2012 @ 11:30:00
Hi thanks for your suggestions!
I hope you don’t mind but I removed the source code you provided because it does not format well in post comments. By all means feel free to post a reference to a formatted source.
Mar 29, 2012 @ 17:14:00
thank you for this script. i just used it to capture 4 of my servers jobs. I have them usually in individual scripts, but have missed some. This ensures that I have external copies of the code for my jobs and i appreciate it.
Mar 29, 2012 @ 19:22:00
Tjay, my pleasure sir! It’s always great to hear from folks who have been able to put my dodgy code to good use
Thanks for your comments.
Jun 13, 2012 @ 20:48:00
Thanks for a great script. We are building out a multi-tiered environment based the setup of one server where there are over a dozen agent jobs. This saved me loads of time.
Jun 13, 2012 @ 22:03:00
Khellian, you’re welcome. Always great to hear of another victory in the battle to automate everything and save time. Thanks for your comments!
Jul 27, 2012 @ 15:58:09
Great Script!! Thanks for Sharing John!!
Jul 31, 2012 @ 19:05:39
My pleasure sir, glad you found it useful. Thanks for your comments!
Jan 11, 2013 @ 02:13:46
Now that you have the jobs scripted out how do you load the jobs with powershell to a SQL Server?
Jan 16, 2013 @ 21:48:58
Jesse, Good question. The reasoning for this script was to create a backup of SQL Server Agent Jobs. In my use case the scripts would simply be run manually on the instance where they were needed.
A PowerShell script could certainly be created in order to automate a restore process.
Jan 28, 2013 @ 04:00:25
Hi John,
I am just beginner to powershell and i need your help to automate one task.
I have 90 Backend servers and still we are in testing phase. You know as of now we are still doing deployment. After deployment completes, i need to execute SQL script which is create JOB script in all 90 servers. As of now we are doing this manually by connecting to every server instance to execute the createbackupjob.sql script.
I know the power shell script to create a JOB in a single server at a time. But i want my Power shell script whcih can execute this CreatebackupJob.Sql script in all 90 backend servers by accepting some serverlist.txt whichin contains all server names.
Please suggest me how can we automate to run .sql script in all 90 servers.
Thank you.
Shafi
Jan 30, 2013 @ 18:14:15
Have you considered using SQLCMD for this requirement instead? You could just create a .bat file that calls 90 SQLCMD statements.
Alternatively, you could just call a SQLCMD statement from within PowerShell using Invoke-Sqlcmd.
Feb 17, 2013 @ 10:50:01
When I have to deploy the same script on more servers, I use SSMS. Put all the servers in a group and just richt click on the group and choose New query.
Sorry, nothing to do with Powershell
Feb 17, 2013 @ 11:49:17
Absolutely using Central Management Server is a great way to run an identical T-SQL script against multiple instances, an excellent suggestion Robbert.
Unfortunately this method will not help Shafi, as he wants to run the distinct T-SQL scripts that are produced for each instance(via the PowerShell script in the post) against arbitrarily defined target instances.
Feb 15, 2013 @ 14:40:24
Here is a powershell suggested topic for you:
Create a powershell script/function that will grab the latest version of a stored procedure in team foundation server and deploy it to a server/database. Would be incredibly useful for dba’s