Getting Services and delete them from powershell

0

I'm almost finished with a powershell script which will search after some services, and delete them if they exist. My problem is that if I use Get-Service on a service that does not exist an exception is thrown, more precise a ServiceCommandException. I've used a try-catch block in my script, but in the log file, it complains about:

CAQuietExec:  The Try statement is missing its Catch or Finally block.
CAQuietExec:  At C:\Program Files (x86)\test\Uninstall.ps1:24 char:2
CAQuietExec:  +      <<<< catch 
CAQuietExec:      + CategoryInfo          : ParserError: (:) , ParseException
CAQuietExec:      + FullyQualifiedErrorId : MissingCatchOrFinally
CAQuietExec:   
CAQuietExec:  Error 0x80070001: Command line returned an error.
CAQuietExec:  Error 0x80070001: CAQuietExec Failed

My script look like this:

$matcherId=1
do 
{
    $matcherIdAsString = [string]$matcherId 
    $matcher = "MatchingServer"+$matcherIdAsString

    try 
    {
        $matcher_service = get-service $matcher
        if($matcher_service -ne $null) 
        { 
            write-host $matcher" is alive"
            $serviceObj =(Get-WmiObject Win32_Service -filter "name='$matcher'")
            if($serviceObj -ne $null) {
                $serviceObj.Delete()
            }
        }
        else 
        {
            write-host "MatchingServer"$matcherIdAsString" is not alive."
        }
    }   
    catch[Microsoft.PowerShell.Commands.ServiceCommandException] 
    {
        write-host "Exception is thrown"
        $error.clear()  
    }
    finally 
    {
        $matcherId++
    }
}
while($matcherId -lt 31)

I cant see why the exception is being handled? What am I doing wrong here?

powershell

1 Answer

1

To avoid error if service is missing you can try:

$matcher_service = get-service $matcher -ea silentlycontinue

no exception will be thrown

answered on Stack Overflow May 22, 2013 by CB.

User contributions licensed under CC BY-SA 3.0