exception - Powershell:捕获无法启动服务时引发的异常

标签 exception service powershell try-catch

我似乎无法捕获 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/

相关文章:

Powershell 选择语句

c# - 使用 System.DirectoryServices.AccountManagement 程序集中的 PrincipalContext 不断获取异常

java - Jenkins Build 因 SVNException 而失败

android - 清除多任务堆栈android时服务破坏

mongodb - 在 Raspberry pi 3 (Debian 9 (stretch)) 上安装 MongoDB 3.2 或更高版本

date - SQL 不接受 PowerShell 日期格式

powershell - Powershell:Start-Transcript仅记录命令而不记录结果

ios - 联系人框架在读取 imageData 时引发异常

python - 为什么 pytest 覆盖会跳过自定义异常消息断言?

java - 我可以将 Guava 的服务与提供 API 的 ExecutorService 一起使用吗?