【问题标题】:Try/catch is not working with Start-ServiceTry/catch 不适用于 Start-Service
【发布时间】:2020-08-20 05:03:58
【问题描述】:

我的问题很简单(我认为)。捕获服务无法启动并抛出消息。实际上,它应该失败的唯一原因是该服务是否被禁用,但我想让用户知道这一点。我saw this post 但似乎没有一个答案有帮助,因为他们正在谈论使用 if 语句过滤捕获,我什至似乎无法像这样获得基本捕获:

Write-Host "Starting Services ..."

    $svc = Get-Service -DisplayName "*lar*" | where { $_.Status -Like "Stop*" }
    if ( $svc )
    {
        foreach ( $item in $svc )
        {
            Write-Host "Starting"$item.Name 
            try { Start-Service $item.Name 
            } 
            catch {
                Write-Host "Could not start service:" $item.Name
            }
        }
    }

我在运行时确实收到了错误,但在 catch 中没有我的 write-host 消息

【问题讨论】:

    标签: powershell


    【解决方案1】:

    Start-Service 在禁用的服务上会引发非终止错误。要使catch 工作,您需要一个终止错误。您可以使用-ErrorAction Stop 强制终止错误。

    try {
        Start-Service $item.Name -ErrorAction Stop
    } 
    catch {
        Write-Host "Could not start service:" $item.Name
    }
    

    【讨论】:

      猜你喜欢
      • 2012-05-14
      • 2017-09-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-28
      • 1970-01-01
      相关资源
      最近更新 更多