Monday 1 February 2021

Power shell script to start, stop and restart windows services.

 With the help you below power shell script you check windows service's status and can restart, stop etc. even on remote servers.


 

[string]$computerName

 

## Create a log file

$LogFile = "E:\Logs\logs_"+(Get-Date).ToString('yyyy-MM-dd')+".txt"

## Count: 3

[string[]]$computerNames ="ServerName1", "ServerName2", "ServerName3"

try {

 #Function that logs a message to a text file

function LogWrite

{   param([string]$Message)

    ((Get-Date).ToString() + " - " + $Message) >> $LogFile;

}

Write-Host "Execution started"

LogWrite -Message "Execution started";

  ForEach ( $computerName in $computerNames ) {

    Write-Host "++++++++++++++++++++++++++++++++++++++++++++" -ForegroundColor Magenta

    try {

     #get a service to check current status

    $svc = get-service -Name "ServiceName" -computername $computerName

      #check if service’s current status is stopped if yes then start it

     if ( $svc.Status -eq "Stopped") {

          (Get-Service -Name "ServiceName" -Computername $computerName).Start();

           Write-Host $computerName -NoNewline

         Write-Host ": the service has started successfully"

         LogWrite -Message "$computerName : the service has started successfully"

         }

         else{

           Write-Host $computerName -NoNewline

           Write-Host ": the service is already up and running"

           LogWrite -Message "$computerName : the service is already up and running"

            }

     }  

        catch {

        LogWrite -Message "$computerName : service reset failed- $_"

        Write-Host ": service start failed"

        Write-Host "Error : $_"

         }

     }

 Write-Host "Execution finished"

 LogWrite -Message "Execution finished"    

 }

    catch {

        LogWrite -Message "$computerName : service reset failed- $_"

        Write-Host ": service start failed"

        Write-Host "Error : $_"

         }