1

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 = ("[email protected]")

$mailmessage.To.add("[email protected]")

$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?

3
  • 2
    you could just pass the name of the task as a parameter to the script
    – SimonS
    Commented Jul 18, 2019 at 14:47
  • 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
    Commented Jul 18, 2019 at 23:02
  • @SimonS Never knew it would be that simple! I will write up the solution myself. Thank you so much for that push.
    – Techidiot
    Commented Jul 19, 2019 at 8:11

1 Answer 1

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 = ("[email protected]")

$mailmessage.To.add("[email protected]")

$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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .