【问题标题】:Powershell to restart a service running longer thanPowershell 重新启动运行时间超过
【发布时间】:2018-06-01 12:55:23
【问题描述】:

我正在尝试编写一个 powershell 脚本,它将:

  • 如果服务已运行超过 1 小时,请重新启动它
  • 如果不到 1 小时,不要理会它
  • 如果它处于stopped 状态,请启动它。

我目前有以下内容,但在添加额外变量和if 语句时,我很糟糕。此脚本运行良好,但我无法重新启动它,似乎只有启动/停止工作。

Get-Service "Print Spooler" | 
    Where StartTime -lt (Get-Date).AddMinutes(-60) |
    Stop-Service

【问题讨论】:

    标签: powershell


    【解决方案1】:

    我会为此建议一个变量:

    # for debugging
    $PSDefaultParameterValues['*Service:Verbose'] = $true
    
    $svc = Get-Service -Name Spooler
    
    if ($svc.Status -eq 'stopped') {
        $svc | Start-Service
    } elseif ($svc.StartTime -lt (Get-Date).AddHours(-1)) {
        $svc | Stop-Service -PassThru | Start-Service
    } else {
        'Print Spooler is running and StartTime is within the past hour!'
    }
    
    # other logic goes here
    

    【讨论】:

    • 你可能想要调整你的逻辑。无论启动时间如何,OP 希望服务在停止时启动。
    • @EBGreen 在他们的要求中,它说如果停止不到一个小时就不要管它,但我可能误解了这一点,因为这个问题有点令人费解。
    • 哦,我读到了,如果服务运行超过一个小时,则重新启动服务,如果服务运行不到一个小时,则不执行任何操作,如果它曾经在,则启动该服务停止状态。完全有可能我也读错了。
    • EBGreen 你说得对。如果服务正在运行并且不到一个小时,请不要理会它,如果它没有运行,则运行它,并且它已经运行了一个多小时,请重新启动它。
    【解决方案2】:

    StartTime 似乎不是 Get-Service 在我的系统上返回的 ServiceController 类的属性。服务的进程 ID 也不是,这很荒谬。这是非常糟糕的设计,但事实就是如此。所以,我会使用 CIM/WMI 来获取进程 ID 以确定服务何时启动。

    $Service = Get-Service "Print Spooler"
    $ServiceStartTime = (Get-CimInstance -ClassName Win32_Service -Filter "Name = '$($Service.Name)'" -Property ProcessId | ForEach-Object { Get-Process -Id $_.ProcessId }).StartTime
    
    # If services has been running for an hour, stop it
    if (($Service.Status -eq 'Running') -and ($ServiceStartTime -lt (Get-Date).AddHours(-1))) {
        Stop-Service $Service
    }
    
    # If service isn't running, start it
    if ($Service.Status -eq 'Stopped') {
        Start-Service $Service 
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-28
      • 2013-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多