How to Use PowerShell and Windows Task Scheduler for a Quick Alerting Solution

Many administrators find themselves responsible for more and more systems as companies grow. Sometimes, this growth is unplanned, and admins become responsible for systems and applications they know little to nothing about.

Because they are not familiar enough with the application to correct systemic errors, administrators are forced to take a reactive approach by fixing errors only after an issue arises — in the worst cases, these can be critical issues that impact the entire organization.

If you find yourself in a position where you need to manage one or more remote servers, and you are experiencing an increasing number of unpredictable errors, you are not alone. The constant assessment, implementation and enablement of new technology in the workplace is fast becoming a challenge for most organizations to manage. It makes sense, then, that more than 50% of respondents in a recent 451 Research survey said they currently work with managed service providers (MSPs) to help fill the gaps and expand coverage.

In the meantime, if you need a quick way to automate alerts and help your team stay ahead of issues, PowerShell in Windows Task Scheduler is an excellent solution.

What Is PowerShell?

PowerShell is Microsoft's most current command-line interface (CLI). It effectively replaced Microsoft's Command Prompt (cmd.exe), which was the CLI for Microsoft computers until the early 2000s. 

Unlike cmd.exe, PowerShell is object-oriented, meaning it focuses on managing data rather than text functions. It uses lightweight commands known as “cmdlets.” 

PowerShell enables you to execute various tasks, including:

  • Extracting information about a computer's OS.
  • Automating administrative tasks for Microsoft products.
  • Moving and removing data to different locations on a computer.
  • Generating CSV and HTML output reports.
  • Reviewing previously executed PowerShell commands.

Another key difference between cmd.exe and PowerShell is that PowerShell has a fully developed scripting language, which lets you write your own script to accomplish specific tasks.

What Is Windows Task Scheduler?

Windows Task Scheduler is a Windows tool that automatically executes predefined tasks when a certain set of conditions is met. This condition could include specific times or system events — whenever the action is convenient for you.

For example, you might schedule a task to run daily backups after hours. Or you might schedule a task to send you an email alert whenever the system detects an error. The Task Scheduler monitors the criteria you set and executes the specified task immediately once those criteria are met.

How To Set Up Alerts with PowerShell and Windows Task Scheduler

It is easier to get started using Task Scheduler for running PowerShell script than it may seem. Because PowerShell offers advanced scripting capabilities, you can get as specific as you need when scripting tasks.

Follow these steps to begin running PowerShell from Task Scheduler.

1. Identify Your Error’s Event:

This solution depends on filtered messages from the Windows Event Log. You must know the Source and the Event ID of the errors for which you want to receive alerts. You can find this information by reviewing the Windows Event Log. 

Use the Get-WinEventLog cmdlet to access historical events and event logs from specific computers within your system. To review logged errors, input “System” as the Log Name and “Error” as the Entry Type. The system presents you with a list of all recent error events that occurred on the computer(s) you wish to work on.

2. Construct a PowerShell Command To Send an Email With Event Log Details

Use this command:

Send-MailMessage -From <from email address> -To <to email address> -Subject <subject line> -SmtpServer <Name or IP of your SMTP server> -BodyAsHtml -Body (Get-EventLog -LogName Application -Source MSSQLServerOLAPService -EntryType Error -Newest 10 | select TimeGenerated, EventID, Message | ConvertTo-Html | Out-String)

The core of this command is PowerShell’s Send-MailMessage. Update the following arguments — including the brackets — for your specific environment:

  • From
  • To
  • Subject
  • SmtpServer

Note: This approach requires that the SmtpServer you specify is available and accepts anonymous relay.

The Body argument is a nested PowerShell command for Get-EventLog. This is where we pull the events from Windows and put them in our email. Update the LogName and Source. This example is pulling the last 10 errors from the application log for the MSSQLServerOLAPService.

3. Test Your Command with PowerShell

The next and final step is to automate this command — if it does not work now, it will never work from the scheduler. 

Because Task Scheduler cannot execute PowerShell commands directly, we need to call PowerShell.exe from our task and tell it to execute our command. We do this by wrapping the command you tested in Step 3 in “&{ }” and passing it with the Command argument. 

A completed example that may be run from the command line looks like this:

PowerShell.exe -Command "&{ Send-MailMessage -From [email protected] -To [email protected] -Subject 'An error has occurred' -SmtpServer -BodyAsHtml -Body (Get-EventLog -LogName Application -Source MSSQLServerOLAPService -EntryType Error -Newest 10 | select TimeGenerated, EventID, Message | ConvertTo-Html | Out-String) }"

Make sure you can run this command from a command prompt and receive an email containing Event Log data before continuing to the next step.

4. Schedule Task to Run PowerShell Script

Schedule your PowerShell command to run whenever an Event with the Event ID you identified in Step 1 is logged. Follow these steps on the server you want to monitor:

  1. Open Task Scheduler
  2. Click “Create Basic Task…”
  3. Enter a name and description
  4. For Trigger, select “When a specific event is logged”
  5. Enter the Log, Source, and Event ID you identified in Step 1
  6. For Action, select “Start a program”
  7. Enter “powershell” in the Program/Script box
  8. Copy and paste everything starting with “-Command” into the Arguments box
  9. Click Next and Finish

5. Test Again

Before you mark this task as completed, it is important to double-check that your system will notify you if an event occurs.

Right-click on your new task and choose Run. This will execute your command and send you an email without waiting for the Event to be fired. If you get the email this time, you can be sure you will receive one the next time your error happens.

If you do not receive an email, you may need to perform some troubleshooting. First, try restarting Task Scheduler. When it starts back up, make sure you have the Startup Type set to Automatic. Then, try to run this test again — if you receive the email, no further action is needed. 

Leverage Managed IT Services from BDO Digital

If you find yourself forced to manage new and unfamiliar administrative tasks, we can help take some of the burden off your shoulders. Our team of IT professionals is skilled in various technologies and business processes, including cloud deployments, data analytics, application development and more, so you can count on us to provide customizable managed services to help you achieve your business's goals.

If you would like to learn more about some of the latest technologies and strategies that are helping IT stay ahead of issues, contact us to discuss your specific environment and business requirements.