0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

パワーシェルを使用したサービスの再起動ツール試作

Posted at

パワーシェルを使用したサービスの再起動ツール

# サービス名の指定
$ServiceName = "YourServiceName"

# サービスの状態確認
$serviceStatus = Get-Service -Name $serviceName

if ($serviceStatus.Status -eq 'Running') {
  Restart-Service -Name $ServiceName -Force
  Write-Host "$serviceName を再起動しました。"
}

if ($serviceStatus.Status -eq 'Stopped') {
  Start-Service -Name $serviceName -Force
  Write-Host "$serviceName を起動しました。"
}


#起動するまで監視>起動できていなければ、停止、開始を行う
$serverStartCheckFlag = false
while($serverStartCheckFlag){
    $serverStartCheckFlag = checkStartService($serviceName)
    

}




## 起動確認
function checkStartService($serviceName){
    # 起動監視用試行回数
    $MaxRetry = 6

    $SericeStartFlag = false

    # 起動中になるまで10秒*6回待機
    for ($i=0; $i -lt $MaxRetry; $i++){
        # 10秒待機
        Start-Sleep -Seconds 10

        # サービス状態確認
        $serviceStatus = Get-Service -Name $serviceName

        # 起動中になっているかを確認する
        if ($serviceStatus.Status -eq 'Running') {
          $SericeStartFlag = true
          break
        }
    }

    return($SericeStartFlag)
}

# 再起動失敗後のリカバリー処理
function recoveryServiceRestart($serviceName){
    $serverStartCheckFlag = false

    # サービス状態確認
    $serviceStatus = Get-Service -Name $serviceName

    if ($serviceStatus.Status -eq 'Running') {
        $serverStartCheckFlag = true
        return($serverStartCheckFlag)
    }

    Stop-Service  -Name $serviceName -Force
    
    if ($serviceStatus.Status -eq 'Stopped') {
        Stop-Service  -Name $serviceName -Force
        Start-Sleep -Seconds 10
    }

    

    return($serverStartCheckFlag)
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?