0

我几乎完成了一个 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)

我看不出为什么要处理异常?我在这里做错了什么?

4

1 回答 1

1

为避免在缺少服务时出错,您可以尝试:

$matcher_service = get-service $matcher -ea silentlycontinue

不会抛出异常

于 2013-05-22T17:30:48.613 回答