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

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 tstark as our operator. We added tstark as an operator in the recipe Adding a SQL Server operator. If you don't have tstark, choose another SQL Server operator that's available in your instance.

How to do it...

Let's look at the steps required to create a SQL Server Job programmatically:

  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:

    $jobName = "Test Job"
    
    #we will drop our test job if it exists already
    if($server.JobServer.Jobs[$jobName])
    {
       $server.JobServer.Jobs[$jobName].Drop()
    }
    
    $job = New-Object -TypeName...