You thought about it, do IT !

Powershell script to restart a service based on the ping of multiple IP addresses

Powershell script to restart a service based on the ping of multiple IP addresses

Had a specific request from a customer, who needed to restart an application service based on the status of its industrial machines.

This application service needed to be restarted on the server each time a machine was newly network connected…

To do that I had to make a simple powershell script

# IPs addresses to check
$ips = "192.168.1.1", "192.168.1.2", "192.168.1.3"

# File paths
$stateFilePath = "C:\Scripts\AutoRestart_Script_Status.txt"
$logFilePath = "C:\Scripts\AutoRestart_Script_Log.txt"

# IP Check
foreach ($ip in $ips) {
    $pingResult = Test-Connection -ComputerName $ip -Count 1 -Quiet
    # Get previous state of this IP
    $previousState = Get-Content -Encoding utf8 $stateFilePath | Where-Object { $_ -like "$ip,*" }

    # Remove this state to update it
    $StateFileContent = Get-Content -Encoding utf8 $stateFilePath | where { $_ -notmatch "$ip,*"}
    Set-Content -Encoding UTF8 -Path $stateFilePath -Value $StateFileContent
    # Ping test
    if ($pingResult) {
        Write-Host "The IP address $ip responds to ping"
        # Check if last state was not responding
        if ($previousState -eq "$ip,not responding") {
            # IP address changed state and is now responding, restart the service
            $DateNow = Get-Date
	    "$DateNow $ip,responding" | Out-File -Encoding UTF8 -Append $logFilePath
	    "$DateNow Restarting service" | Out-File -Encoding UTF8 -Append $logFilePath
            Write-Host "Restarting service"
	    Restart-Service -DisplayName "MyServiceToRestart"
        }
        # Update states on the file
        "$ip,responding" | Out-File -Encoding UTF8 -Append $stateFilePath
    } else {
        Write-Host "The IP address $ip does not respond to ping"
        # Update states on the file
        "$ip,not responding" | Out-File -Encoding UTF8 -Append $stateFilePath
    }
}

The file AutoRestart_Script_Status.txt contains one line for each IP with its status.

The file AutoRestart_Script_Log.txt contains newly pinged IP and time of service restart

do-it.dev Avatar

[wpedon id=198]

Leave a Reply

Your email address will not be published. Required fields are marked *

Aurélien Bordinat

I am a french computer engineer, adept of DIY, home automation and new technologies. When i’m not busy trail running, i spend some time prototyping.