[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"
}
Advertisements
This entry was posted in Powershell, Scripting and tagged , . Bookmark the permalink.

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 )

Google+ photo

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

Twitter picture

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

Facebook photo

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

w

Connecting to %s