我似乎无法捕获 Start-Service
引发的异常。这是我的代码:
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]
时,异常将被捕获并打印“got here”。
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"
}
最佳答案
Try/Catch 仅适用于终止错误。使用值为 Stop 的 ErrorAction 参数使错误成为终止错误,然后您就能够捕获它:
try
{
start-service "SomeUnStartableService" -ErrorAction Stop
}
catch
{
write-host "got here"
}
更新:
当您将 $ErrorActionPreference 设置为“stop”(或使用 -ErrorAction Stop)时,您得到的错误类型是 ActionPreferenceStopException,因此您可以使用它来捕获错误。
$ErrorActionPreference='stop'
try
{
start-service SomeUnStartableService
}
catch [System.Management.Automation.ActionPreferenceStopException]
{
write-host "got here"
}
}
关于exception - Powershell:捕获无法启动服务时引发的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6676483/