PoshCode Archive  Artifact [40dcbe77b2]

Artifact 40dcbe77b2aa23cf666e0682452a29206562bc7e3accecb75c002e58ad13ca5d:

  • File validate-an-IP-address.ps1 — part of check-in [749380c024] at 2018-06-10 14:18:13 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: 1075)

# encoding: ascii
# api: powershell
# title: validate an IP address
# 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: 0.1
# author: mow01
# license: CC0
# x-poshcode-id: 6592
# x-archived: 2017-03-18T05:49:17
# x-published: 2017-10-25T01:08: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)