Monitoring your infrastructure is an extremely important aspect of managing your systems. If services go down, IT needs to find this out as soon as possible so they can begin the process of bringing them back up. This is common practice for system administrators. To monitor systems there are a slew of tools available. Some of these include Nagios, Monitis, and WhatsUp Gold. However, with the PowerShell script in this post, you can quickly set up your own flexible monitoring solution.
PowerShell service cmdlets
PowerShell provides the ability to query, start, stop, restart, set, and even create Windows services. For instance, to get the current status of the remote registry service, we can simply run:
I can see the current status is “Stopped” as well as see other properties such as the dependent services. For the purposes of monitoring services, we will only be using Get-Service, but to start the remote registry service, I can run Start-Service:
Get-PSServiceStatus function overview
Using Get-Service allows us to get the service status both locally and remotely, but we also want the capability to receive alerts via email if the status of a service has changed. We can do this with Send-MailMessage as you will see in the function.
Normally, enterprise products use a database to keep track of the status on each polling and then send an alert if the status has changed. While this is still possible with PowerShell, I will keep it simple by only keeping track of the last status polled. To do this, I’ll use the presence of a text file and send an alert if that has changed. The flow of this function goes:
- For each computer, check to see if a text file is present and if a service is running. An existing text file indicates the service was not running on the previous monitoring attempt.
- If the service is not running and the text file is present, do nothing since the status has not changed.
- If the service is not running and no text file is present, create the text file and send an email alert stating the service is not running.
- If the service is running and the text file is present, delete the text file and send an alert that the service is now running.
- If the service is running and the text file is not present, do nothing.