Quantcast
Channel: Windows PowerShell Forum
Viewing all articles
Browse latest Browse all 2562

Monitoring Long Running Scheduled Tasks

$
0
0

Hi Everyone!

I found a fantastic ps script that will monitor a long running scheduled task...the link is here: Original Script

After a bit of tweaking, I got this running perfectly...but can only set it up for watching one scheduled task. The script looks at the $server and pulls in the scheduled tasks information into a CSV and puts that CSV into the $scriptpath. It looks for the $scheduledtask value and if it exceeds the $maxminutes it sends an email. I'd like to be able to have the script look at several scheduled tasks but do not know enough about powershell to "loop" through a list of tasks and send an email out for any of those tasks that meets the criteria for sending an email alert.

So basically I need some help tweaking this script to monitor a few scheduled tasks instead of just one.

Thank you so much for looking at this with me. Here's the working script for monitoring one task:

$server = "Server_Name"
$scheduledtask="Test Task"
$maxminutes="5"
$scriptpath = "C:\Path_To\Script"

# Send email function

function sendEmail {

$from = New-Object System.Net.Mail.MailAddress "abc@def.com";

$to = New-Object System.Net.Mail.MailAddress "abc@def.com";

$mail = New-Object System.Net.Mail.MailMessage $from, $to;

$mail.Subject = "Scheduled Task ( $scheduledtask ) on $server has been running for longer than $maxminutes minutes.";

$mail.Body = "Scheduled Task ( $scheduledtask ) on $server has been running for longer than $maxminutes minutes. Total Runtime for ( $scheduledtask ): $datediff .";

# Connect to mail relay

$smtpserver = "smtp.server.com"

$smtp = New-Object System.Net.Mail.SmtpClient ($smtpserver);

# Send Email

$smtp.Send($mail);

}

schtasks /query /s $server /FO CSV /v > "$scriptpath\ScheduleTaskMon.csv";

$longrunning = Import-Csv "$scriptpath\ScheduleTaskMon.csv" |

Where-Object {[DateTime]$_."Last Run Time" -and $_."Status" -eq "Running" -and $_."TaskName" -eq "$scheduledtask"};

$datediff=([DateTime]::Now)-([DateTime]$longrunning."Last Run Time");

if ($datediff -le 0)

{exit}

if (($datediff.TotalMinutes) -gt $maxminutes)

{sendemail};



Viewing all articles
Browse latest Browse all 2562

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>