2013-10-02 43 views
1

的渔获结果当运行一个脚本:PowerShell的重启服务cmdlet的

Restart-Service ServiceName 

如何捕捉的结果?例如,如果服务不存在,我会得到这样的消息:

Restart-Service : Cannot find any service with service name 'ServiceName'. 

我使用if ($error),但没有运气试图trycatch

回答

3

您可以查看ErrorAction参数。如果你只是不想要一个错误,你可以尝试以下(检查$?看看它是否成功)。

Restart-Service ServiceName -ErrorAction SilentlyContinue 

尝试捕捉并不能捕捉到所有错误,只能终止错误。如果您想在终止错误中打开错误,您可以尝试以下操作。

try 
{ 
    Restart-Service ServiceName -ErrorAction Stop 
} 
catch 
{ 
    'Catched' 
} 
0

要获得最后一个错误:

$error[0]