Monday, March 23, 2015

Make sure my Windows Service is enabled and running

The situation

I recently had a need to keep the ASP.NET State Service (aspnet_state) running. For some reason it was getting disabled and stopped sometimes. I assume a corporate security policy is doing it periodically, but I don't know exactly how or why it happens. However, I do know that every time the ASP.NET State Service goes down so does my web applications on my web farm because they are using the ASP.NET State Service.

The Workaround

Luckily, PowerShell makes it very easy to set the StartupType to Automatic and then start a Windows Service. No need to test state before calling since it seems to only change something if it is needed.

Set-Service -name aspnet_state -StartupType Automatic
Set-Service -name aspnet_state -Status Running

Save the two above lines in a file with any name you like ending in .ps1. I'll use EnsureStateService.ps1 for this example.

Automating the workaround

Every minute I want to execute the above PowerShell file. That way at most I will have 1 minute of downtime (minus the time it takes to enable and start the ASP.NET State Service). To create a scheduled task in Windows Task Scheduler do the following:

1. Create a task
2. Set the task to be executed as the user System.
3. I used Windows Vista, Windows Server 2008 configuration, but I don't think it matters in this case.
4. For the trigger, I set it to run Daily, running every 1 days, Repeated task every 1 minute, and stopped task if running for more than 1 minute as shown below:


5. For the Action, do the following:
For Program/script field enter PowerShell
For Add argument (optional): field enter the path to the powershell script file surrounded by double-quotes. In this example, it is "D:\MDM\EnsureStateService.ps1"