[powershell]Check valid ip address, subnet or ip address range.

Here’s a code to check valid ip address (host address), subnet and ip address range in powershell.

Sample code, sample code can be made as a function to return boolean values when testing an input:

#ip address validation solution reference (Kamil Tatar):
#https://powershell.org/forums/topic/detecting-if-ip-address-entered/
#test input
$a = 192.168.1.10
$ipcheck = ($a -as [IPaddress]) -as [Bool]
if($ipcheck)
{
    write-host "Valid ip address"
}
elseif($a -like "*/*" -or $a -like "*-*")
{
    $cidr = $a.split("/")
    if($cidr[1] -ge '0' -and $cidr[1] -le '32')
    {
        write-host "valid subnet"
    }
    elseif($a -like "*-*")
    {
        $ip = $a.split("-")
        $ip1 = $ip[0] -as [IPaddress] -as [Bool]
        $ip2 = $ip[1] -as [IPaddress] -as [Bool]
        if($ip -and $ip)
        {
            write-host "valid ip address range"
        }
        else
        {
            write-host "invalid range"
        }

    }
    else {
        write-host "invalid subnet"
    }
}
else
{
    write-host "not valid address"
}
Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s