获取服务并从powershell中删除它们

时间:2013-05-22 17:15:12

标签: powershell

我差不多完成了一个PowerShell脚本,它将搜索一些服务,并删除它们(如果存在)。我的问题是,如果我在不存在的服务上使用Get-Service,则会抛出异常,更精确的是ServiceCommandException。我在我的脚本中使用了try-catch块,但是在日志文件中,它抱怨:

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

我的脚本看起来像这样:

$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)

我无法理解为什么要处理异常?我在这里做错了什么?

1 个答案:

答案 0 :(得分:1)

如果缺少服务以避免错误,您可以尝试:

$matcher_service = get-service $matcher -ea silentlycontinue

不会抛出异常