Getting the Scheduled Task Name which activated the PowerShell Script

0

This might be an easy one but I tried hard to find "how to" and didn't came across any answers. So, my question is, "How do I find the Scheduled Task Name which activated my Powershell script"

So, I have a Scheduled Task configured on my Windows 2012 R2 Server which run's a program XYZ and also executes a Powershell script to send an email notification with the name of Task hard-coded inside the script.

$SmtpClient = new-object system.net.mail.smtpClient

$MailMessage = New-Object system.net.mail.mailmessage

$SmtpClient.Host = "smtp.mydomain.com"

$mailmessage.from = ("myemail@mydomain.com")

$mailmessage.To.add("myname@mydomain.com")

$mailmessage.Subject = “Task XYZ has started”

$mailmessage.Body = “This is to notify that task XYZ has been started”

$smtpclient.Send($mailmessage)

Now, I have 100 different tasks which needs this email notification and I have to use only a single PowerShell Script to trigger the email. This email should consist of the name of the Scheduled Task inorder to understand which Task has been started running for which we are receiving the email notification.

So, is there any inbuilt Powershell variable/function to find the name of Scheduled Task which executed my Powershell script?

Techidiot

Posted 2019-07-18T09:08:45.287

Reputation: 161

2you could just pass the name of the task as a parameter to the script – SimonS – 2019-07-18T14:47:49.977

Do these tasks overlap, are any of them running at the same time as any others? If not you could key in on the running state and report the name from there. SimonS's answer is probably the best idea though. – DBADon – 2019-07-18T23:02:50.237

@SimonS Never knew it would be that simple! I will write up the solution myself. Thank you so much for that push. – Techidiot – 2019-07-19T08:11:55.617

Answers

3

Thanks to SimonS for providing the solution in the comment. Here's what I did for anyone who wants to do this in future -

I modified my Powershell Script as follows -

Function Send_Email([string[]$TaskName)
{
$SmtpClient = new-object system.net.mail.smtpClient

$MailMessage = New-Object system.net.mail.mailmessage

$SmtpClient.Host = "smtp.mydomain.com"

$mailmessage.from = ("myemail@mydomain.com")

$mailmessage.To.add("myname@mydomain.com")

$mailmessage.Subject = “Task $TaskName has started”

$mailmessage.Body = “This is to notify that task $TaskName has been started”

$smtpclient.Send($mailmessage)

}

Send_Email $args

Now, in the Scheduled Task I have an action defined with below things -

  • Action Type - Start a Program
  • Program Name - Powershell.exe
  • Arguments - C:\Temp\Send_Email.ps1 'Send_Email_Task'

Now, when the Scheduled Task starts, it executes my Powershell Script with the Task name. This way I can use this same script for all my tasks.

Techidiot

Posted 2019-07-18T09:08:45.287

Reputation: 161