PoshCode Archive  Artifact [5b085b3283]

Artifact 5b085b3283513984b9ec54afea74bc7591579f6143df88155785de5bdefc1639:

  • File validate-an-IP-address.ps1 — part of check-in [7711767af1] at 2018-06-10 14:01:16 on branch trunk — Uses [system.net.IPAddress]::parse, not [system.net.IPAddress]::tryparse. (user: mow01 size: 902)

# encoding: ascii
# api: powershell
# title: validate an IP address
# description: Uses [system.net.IPAddress]::parse, not [system.net.IPAddress]::tryparse.
# version: 127.1
# author: mow01
# license: CC0
# x-poshcode-id: 5781
# x-derived-from-id: 5782
# x-archived: 2016-03-17T03:21:50
# x-published: 2016-03-12T06:46:00
#
# The result is then tested against the original parameter.
#
# validate given IP address as an IPAdress (given string input)
PARAM($ip=$(read-host "Enter any IP Address"))

try
{
    #parse fills missing octets with zeros in the order of 3rd, 2nd, 1st
    #("127.1" becomes "127.0.0.1") ("192.168.1" becomes "214.0.0.1") ("1" becomes "0.0.0.1")

    #test if converted IP matches original IP. If invalid, throws MethodInvocationException
    return [system.net.IPAddress]::parse("$ipAddress").IPAddressToString -eq "$ipAddress"
}
catch{return $false}