2011-07-13 60 views
7

我似乎無法捕獲Start-Service拋出的異常。這裏是我的代碼:Powershell:無法啓動服務時拋出捕獲異常

try 
{ 
    start-service "SomeUnStartableService" 
} 
catch [Microsoft.PowerShell.Commands.ServiceCommandException] 
{ 
    write-host "got here" 
} 

當我運行此,拋出異常,但沒有抓到:

*Service 'SomeUnStartableService' start failed. 
At line:3 char:18 
+  start-service <<<< "SomeUnStartableService" 
    + CategoryInfo   : OpenError: (System.ServiceProcess.ServiceController:ServiceController) [Start-Service], ServiceCommandException 
    + FullyQualifiedErrorId : StartServiceFailed,Microsoft.PowerShell.Commands.StartServiceCommand* 

$ErrorActionPreference設爲停止,所以這不應該成爲問題。

當我將我的代碼更改爲catch [Exception]時,將捕獲異常並打印「到此處」。

請問start-service丟了ServiceCommandException還是別的什麼?它看起來好像是但我無法抓住它!

---編輯---

理想我可以寫以下,並拋出一個異常,如果start-service沒有拋出異常,只有捕獲由start-service拋出的異常:

try 
{ 
    start-service "SomeUnStartableService" 
    throw (new-object Exception("service started when expected not to start")) 
} 
catch [Microsoft.PowerShell.Commands.ServiceCommandException] 
{ 
    write-host "got here" 
} 

回答

1

我平時不要不會限制捕捉範圍本身,而是處理與閉鎖塊內的邏輯測試的例外:

try 
{ 
    start-service "SomeUnStartableService" -ea Stop 
} 
catch 
{ 
    if ($error[0].Exception -match "Microsoft.PowerShell.Commands.ServiceCommandException") 
    { 
     #do this 
    } 
    else 
    { 
     #do that 
    } 
} 

也許不乾淨,並可能導致巨大的catch塊。但如果它的工作...;)

+0

這是一個恥辱,它不像捕捉特定的異常那樣整潔,但我想如果不能做到這是次最好的事情。 – Jack

10

Try/Catch僅適用於終止錯誤。如何使用ErrorAction參數與停止的值,使錯誤終止錯誤,然後你就可以抓住它:

try 
{ 
    start-service "SomeUnStartableService" -ErrorAction Stop 
} 
catch 
{ 
    write-host "got here" 
} 

UPDATE:

當您設置$ ErrorActionPreference到「停止」(或者使用-ErrorAction Stop)你得到的錯誤類型是ActionPreferenceStopException,所以你可以使用它來捕獲錯誤。

$ErrorActionPreference='stop' 

try 
{ 
    start-service SomeUnStartableService 
} 
catch [System.Management.Automation.ActionPreferenceStopException] 
{ 
    write-host "got here" 
} 

}

+0

如果$ ErrorActionPreference設置爲停止它是不夠的? – JPBlanc

+0

由於$ ErrorActionPreference設置爲'Stop',所以添加-erroraction Stop沒有任何區別。上面的代碼捕獲了一個通用的[Exception],但是我希望只捕獲start-service拋出的異常,這意味着我可以在try塊中拋出另一個異常,但不能捕獲它。 – Jack

+0

對不起,錯過了那部分。我已經更新了線程,請檢查一下。 –

0

要發現你的異常時,您可以使用:

try 
{ 
    start-service "SomeUnStartableService" -ea Stop 
} 
catch 
{ 
$_.exception.gettype().fullname 
} 

編輯:這是一種旁路與SystemException

try 
{ 
    start-service "SomeUnStartableService" -ea Stop 
} 
catch [SystemException] 
{ 
write-host "got here" 
} 
+0

這會返回Microsoft.PowerShell.Commands.ServiceCommandException,這正是我上面想要捕獲的內容。 – Jack

+0

編輯確實有幫助,我認爲符合目的,所以我投了票,但我不認爲這可能是答案,因爲它是一種解決方法。 – Jack