Monday, July 9, 2012

Check if service is installed in Powershell

Recently I needed to check if IIS was installed on a machine using Powershell.

The obvious way of doing this is:

$iis = Get-Service W3SVC

if ($iis -eq $NULL)
{
"IIS not found"
}


The problem with this is that it does not really work, since the first line will crash if the service is not found.
The solution for this is to make it fail silently.


$iis = Get-Service W3SVC -ErrorAction SilentlyContinue
if ($iis -eq $NULL)
{
"IIS not found"
}

This makes it fail silently, and the code works as expected!

2 comments:

Andrea said...

THANK YOU! I was getting so frustrated at getting around the error message. I was just resigned to accepting the error as an indicator that IIS was not installed. It worked, but wasn't pretty. I like this solution MUCH better.

Reuben Bartolo said...

You're welcome. :) So glad to have helped someone. That's why I keep this blog.