Powershell to restart a service

Recently I had a service on a server that keeps stopping, and I needed to check to make sure it's started, and if not then I need to restart it. To fix this I wrote a powershell script to do this, and then put it on a scheduled task to run it regularly.

I created a PowerShell script like this one, and saved it to the hard drive as RestartService.ps1
$ServiceName = 'Serenade'
$arrService = Get-Service -Name $ServiceName

while ($arrService.Status -ne 'Running')
{

    Start-Service $ServiceName
    write-host $arrService.status
    write-host 'Service starting'
    Start-Sleep -seconds 60
    $arrService.Refresh()
    if ($arrService.Status -eq 'Running')
    {
        Write-Host 'Service is now Running'
    }

}

Then I opened Task Scheduler, and I created a task that runs this script. The actions for the script are like this:

  • Actions: Start a program
  • Program/Script: PowerShell.exe
  • Add arguments: -ExecutionPolicy Bypass -File RestartService.ps1 -skipadmincheck
  • Start in: D:\PowerShell
The "Start in" location is where you saved the PowerShell script.

Now you have a scheduled task that will check this service on the schedule that you define.

Share on Google Plus

About Tom DeMeulenaere

Highly accomplished information technology professional with extensive knowledge in System Center Configuration Manager, Windows Server, SharePoint, and Office 365.
    Blogger Comment

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.