Creating a SQL Server job
In this recipe, we will create a simple SQL Server job programmatically.
Getting ready
We are going to create a simple job called Test Job
, and set up jraynor
as our operator. If you don't have jraynor
, choose another SQL Server operator that's available in your instance.
How to do it...
Open the PowerShell console by going to Start | Accessories | Windows PowerShell | Windows PowerShell ISE.
Import the
SQLPS
module and create a new SMO Server object, as follows:#import SQL Server module Import-Module SQLPS -DisableNameChecking #replace this with your instance name $instanceName = "KERRIGAN" $server = New-Object -TypeName Microsoft.SqlServer.Management.Smo.Server -ArgumentList $instanceName
Add the following script and run:
$jobName = "Test Job" if($server.JobServer.Jobs[$jobName]) { $server.JobServer.Jobs[$jobName].Drop() } $job = New-Object -TypeName Microsoft.SqlServer.Management.SMO.Agent.Job -ArgumentList $server.JobServer, $jobName #Specify which operator...