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

Adding a SQL Server event alert


In this recipe, we'll see the steps for adding a SQL Server event alert.

How to do it...

Let's list the steps required to complete the task:

  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
    #for purposes of our exercise, we will drop this
    #alert if it  already exists
    $alertname = "Test Alert"
    $alert = $jobserver.Alerts[$alertname]
    
    #if our test alert exists, we will drop it first
    if($alert)
    {
      $alert.Drop()
    }
    
    #Alert accepts a JobServer and an alert name
    $alert  = New-Object  Microsoft.SqlServer.Management.Smo.Agent.Alert $jobserver, $alertname
    $alert.Severity = 10
    
    #Raise Alert when Message contains
    $alert.EventDescriptionKeyword...