Running a SQL Server job
This recipe demonstrates how you can run a SQL Server job programmatically.
Getting ready
In this recipe, we assume you have a job in your development environment called Test Job
that you can run. If not, pick another job in your system that you can run.
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:
$jobserver = $server.JobServer $jobname ="Test Job" $job = $jobserver.Jobs[$jobname] $job.Start() #sleep to wait for job to finish #check last run date Start-Sleep-s1 $job.Refresh() $job.LastRunDate
How it works...
The first step is to get a handle to your instance...