PoshCode Archive  Artifact [f735e834f2]

Artifact f735e834f2a223f1c559c5125d081b355186869b9b86439d5ad3f13c330ffb7e:

  • File REALLY-validates-given-IP-address-.ps1 — part of check-in [3400bec272] at 2018-06-10 14:02:30 on branch trunk — REALLY validates given IP address and returns True/False. The original script didn’t allow ZEROS in the Ip address (eg: 127.0.0.1 returned $false) (user: mow01 size: 1062)

# encoding: ascii
# api: powershell
# title: 
# description: REALLY validates given IP address and returns True/False.  The original script didn’t allow ZEROS in the Ip address (eg: 127.0.0.1 returned $false)
# version: 172.30.2.112
# author: mow01
# license: CC0
# x-poshcode-id: 5841
# x-archived: 2016-09-07T04:22:20
# x-published: 2016-05-02T07:28:00
#
# now without trap
#
# validate given IP address as an IPAdress (given string input)
PARAM($IP=$(read-host "Enter any IP Address"))

## YOU could do this, but ...
# $IP -match "(\d{1,3}).(\d{1,3}).(\d{1,3}).(\d{1,3})" -and -not ([int[]]$matches[1..4] -gt 255)

## you shouldn't parse things yourself when it's in the framework. You might make a mistake ;-)
#trap { return $false }
#[IPAddress]$IP  # Just cast it to an IPAddress ... if it's valid, it will work.
#return $true

## no trap needed if tryparse is used 

#[system.net.IPAddress]::tryparse($ip,[ref]$null)

# when you still need the parsed IP number :

[ref]$a = $null
[system.net.IPAddress]::tryparse($ip,$a)