Book Image

SQL Server 2014 with PowerShell v5 Cookbook

By : Donabel Santos
Book Image

SQL Server 2014 with PowerShell v5 Cookbook

By: Donabel Santos

Overview of this book

Table of Contents (21 chapters)
SQL Server 2014 with PowerShell v5 Cookbook
Credits
About the Author
Acknowledgments
About the Reviewers
www.PacktPub.com
Preface
Index

Running an SQL Server Job


In this recipe, we will see how you can run a SQL Server Job programmatically.

Getting ready

In this recipe, we assume you have a job called Test Job in your development environment that you can run. This was created in the Creating a SQL Server Job recipe. If you do not have this job, pick another job in your system that you can run.

How to do it...

These are the steps to run a SQL Server Job:

  1. Open PowerShell ISE as administrator.

  2. Import the SQLPS module and create a new SMO Server Object:

    #import SQL Server module
    Import-Module SQLPS -DisableNameChecking
    
    #replace this with your instance name
    $instanceName = "localhost"
    $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 -s 1
    $job.Refresh()
    $job.LastRunDate

How it works...

The...