join the MSSQLTips community

Today's Site Sponsor


 

SQL defrag manager quickly pinpoints fragmentation “hot spots” and automates defragmentation- saving hours of time!
 


Checking SQL Server Agent jobs using Windows PowerShell
Written By: Edwin Sarmiento -- 7/21/2009 -- 0 comments -- printer friendly -- become a member



Accelerate, compress and encrypt database backups

            Free SQL Server Books  -----  Looking for help with your SQL Server career?            

Problem
Checking for SQL Server Agent jobs and their status is part of your daily task as a DBA. How do we use Windows PowerShell to check for SQL Server Agent jobs?

Solution
Similar to the task described in the tip Check the Last SQL Server Backup Date using Windows PowerShell, it would require reading the tables in the msdb database and joining them appropriately to find out which jobs failed. Two tables in particular are of interest to us to check for job execution information like job name, execution status, run date, run time, etc. - the sysjobs and sysjobhistory tables. 

The script below displays a list of jobs on your SQL Server instance with there status.

USE msdb 
GO 
SELECT 
   
j.[name] AS [JobName]
   
run_status CASE h.run_status 
   
WHEN THEN 'Failed'
   
WHEN THEN 'Succeeded'
   
WHEN THEN 'Retry'
   
WHEN THEN 'Canceled'
   
WHEN THEN 'In progress'
   
END,
   
h.run_date AS LastRunDate,  
   
h.run_time AS LastRunTime
FROM sysjobhistory h 
   
INNER JOIN sysjobs j ON h.job_id j.job_id 
       
WHERE j.enabled 1  
       
AND h.instance_id IN 
       
(SELECT MAX(h.instance_id
           
FROM sysjobhistory h GROUP BY (h.job_id))
GO 

Notice that the run_date and run_time columns of the sysjobhistory table are of type int and would be a bit challenging to convert the columns to their appropriate data types.  Server Management Objects (SMO) exposes these properties when using Windows PowerShell. The JobServer property of the Server object represents the SQL Server Agent associated with an instance of SQL Server. This includes the SQL Server jobs, operators and alerts.

When translating the T-SQL query above to Windows PowerShell, we would be interested in the Name, LastRunDate and LastRunOutcome properties of the Jobs object. What's really good to note is that the LastRunDate property is in a datetime format that no longer requires conversion to the appropriate data type, similar to what we get from the sysjobhistory table in the msdb database.  I keep trying to highlight this for every tip I've written that uses PowerShell with SMO.  The only aspect of the code that we have changed from the scripts in the previous tips is the last line, i.e. adding new properties for the new objects we are working with. This highlights the power and simplicity of Windows PowerShell from the script.

[System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
$rvs = New-Object ('Microsoft.SqlServer.Management.Smo.Server') "LOCALHOST\SQL2000"

#Create an instance of the Jobs object collection from the JobServer property
#And pipes that to the filter Where-Object cmdlet to retrieve only those jobs that are enabled but failed
$srv.JobServer.Jobs | Where-Object {$_.IsEnabled -eq $TRUE} | Select Name,LastRunOutcome, LastRunDate
 

Notice that the LastRunDate property is in the correct data type. The LastRunOutcome property is returned as they are without the need for further translations as in the T-SQL script above. Let's call to the Excel object as we did in the previous tips to format the results. Again, the script above is more than enough for what we need.

#Create a new Excel object using COM
$Excel = New-Object -ComObject Excel.Application
$Excel.visible = $True

$Excel = $Excel.Workbooks.Add()
$Sheet = $Excel.Worksheets.Item(1)

#Counter variable for rows

$intRow = 1

#Read thru the contents of the SQL_Servers.txt file
foreach ($instance in get-content "D:\SQL_Servers.txt")
{

     #Create column headers
     $Sheet.Cells.Item($intRow,1) = "INSTANCE NAME:"
     $Sheet.Cells.Item($intRow,2) = $instance
     $Sheet.Cells.Item($intRow,1).Font.Bold = $True
     $Sheet.Cells.Item($intRow,2).Font.Bold = $True

     $intRow++

      $Sheet.Cells.Item($intRow,1) = "JOB NAME"
      $Sheet.Cells.Item($intRow,2) = "LAST RUN OUTCOME"
      $Sheet.Cells.Item($intRow,3) = "LAST RUN DATE"

     #Format the column headers
     for ($col = 1; $col –le 3; $col++)
     {
          $Sheet.Cells.Item($intRow,$col).Font.Bold = $True
          $Sheet.Cells.Item($intRow,$col).Interior.ColorIndex = 48
          $Sheet.Cells.Item($intRow,$col).Font.ColorIndex = 34
     }

     $intRow++
      #######################################################
     #This script gets SQL Server Agent job status information using PowerShell

     [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null

     # Create an SMO connection to the instance
     $srv = New-Object ('Microsoft.SqlServer.Management.Smo.Server') $instance

     $jobs=$srv.JobServer.Jobs

     #Formatting using Excel


ForEach ($job in $jobs
{

       #
 Formatting for the failed jobs
       
if ($job.LastRunOutcome -eq 0)
       
{
           $fgColor 
3
       }
       
else
       
{
           $fgColor 
0
       }
   

       $Sheet.Cells.Item($intRow1=  $job.Name
       $Sheet.Cells.Item
($intRow2$job.LastRunOutcome.ToString()
       $Sheet.Cells.item
($intRow2).Interior.ColorIndex $fgColor
       $Sheet.Cells.Item
($intRow3=  $job.LastRunDate

   
           
       $intRow 
++
   

}
   $intRow 
++


}

$Sheet.UsedRange.EntireColumn.AutoFit()
cls

 

Next Steps

Readers Who Read This Tip Also Read Comment or Ask Questions About This Tip Twitter This Tip!


Free SQL Server performance monitoring dashboard – Idera SQL check

New! SQL Object Level Recovery Native from Red Gate. Save time and disk space. Download a free trial.

Are you looking for more help?

Get SQL Server resources and real-time expert advice at Quest Connect 2009 – the free, virtual event

Make the most of MSSQLTips...Sign-up for the newsletter

Free Whitepaper - The Seven Steps to Successful SQL Server Auditing


 

 


 

 

 

 

DB Nitro - SQL Nitro

SQL Nitro sits between SQL Server & its clients, optimizing the normally inefficient TDS protocol. Optimize TDS & compress the data up to 80%, reduce SQL bandwidth by 50%, & improve response times over 65%!

Download now!

 

 

 

 

More SQL Server Tools
SQL Nitro

SQL Refactor

SQL safe backup

SQL defrag manager

SQL Backup

 

 

 

 



Copyright (c) 2006-2009 Edgewood Solutions, LLC All rights reserved
privacy statement | disclaimer | copyright | advertise | write for mssqltips | feedback | about
Some names and products listed are the registered trademarks of their respective owners.