PoshCode Archive  Artifact [33f1a4010a]

Artifact 33f1a4010af5b26162ff765be81210e7f3be9d836e978a3b73ec963abd50e73d:

  • File validate-an-IP-address.ps1 — part of check-in [af059c9edd] at 2018-06-10 14:01:17 on branch trunk — Uses [system.net.IPAddress]::parse, not [system.net.IPAddress]::tryparse. (user: Allan B size: 879)

# encoding: ascii
# api: powershell
# title: validate an IP address
# description: Uses [system.net.IPAddress]::parse, not [system.net.IPAddress]::tryparse.
# version: 127.1
# author: Allan B
# license: CC0
# x-poshcode-id: 5782
# x-archived: 2016-03-05T06:12:54
# 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 "192.168.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}