Batch Check Machines Up/Down in IP ranges using Powershell


The best way to learn a new language is to practise. The Powershell is a powerful scripting tool on Windows (especially for Windows Server Editions). With a few knowledge, you can write useful scripts in Powershell.

The following Powershell will get the IP ranges from the command line and check if machines given in this range (only the last digit of IP changes) is up or down. It is useful to batch test the machines in Local Access Network. The IP addresses containing 0 and 255 are not specific so these two are excluded when enumerating the IP addresses. You can pass multiple IP ranges to this Powershell utility.

It is based on the ping utility where when success, it returns 0. If it can’t be pinged, the error code will be set to 1. The -n 1 for ping specifies to try only once per IP address, which speeds up the checking process. In DOS batch, you can check %errorlevel% for last exit code from program, but on Powershell, you should use variable $LASTEXITCODE to get this value.

The $? is True if last operation succeeded and False otherwise. The $LASTEXITCODE contains the exit code of the last Win32 executable.

<#
    A Powershell Script to check machines are up/down in a IP
    Example: PPing 192.168.0 192.168.3
    https://HelloACM.com
#>

if  ($args.count -eq 0) {
    Write-Host "Example: PPing 192.168.0"
    exit
}

for ($j = 0; $j -lt $args.count; $j ++) {
    # loop current ip range    
    $ip = $args[$j] + "."
    for ($i = 1; $i -lt 255; $i ++) {
        # get each ip
        $cur = $ip + $i
        # ping once 
        ping -n 1 $cur | Out-Null
        if ($LASTEXITCODE -eq 0) {
            Write-Host "$cur is up"
        } else {
            Write-Host "$cur is down"
        }
    }
}

We use variable $args in Powershell to access the command line arguments. The property count returns the number and you can use array indexer to get each argument. The index starts at zero i.e. $args[0] refers to the first argument.

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
388 words
Last Post: HTML Hyper Link in New Windows by XHTML 1.0 standard
Next Post: Resharper Helps to Find Bug - Enum Type Not Equal to Null Forever

The Permanent URL is: Batch Check Machines Up/Down in IP ranges using Powershell

One Response

Leave a Reply