Tuesday, June 14, 2011

Validate IPv4 Addresses in PowerShell

Here is a simple function to validate if a IPv4 address meets the RFC. It does not confirm if the host associated to the IP Address is accessible. To do that with PowerShell, you need to utilize the System.Net.NetworkInformation.Ping class. The validation is performed by a fairly complex Regular Expression using '-match'.
Function Test-IPv4Address($ipAddress) {
 if($testAddress -match "\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\b") {
  $addressValid = $true
 } else {
  $addressValid = $false
 }
 return $addressValid
}
#--------------------------------------------------------------------------------------------------#
Set-Variable -name testAddresses -option Constant -value @("192.168.1.1","546.23.10.12","8.8.8.8","127.0.999.26")
#--------------------------------------------------------------------------------------------------#
foreach($testAddress in $testAddresses) {
 if((Test-IPv4Address $testAddress)) {
  Write-Host "$testAddress is a validly formatted IPv4 Address" -foregroundColor Green
 } else {
  Write-Host "$testAddress is not a validly formatted IPv4 Address" -foregroundColor Red
 }
}

No comments:

Post a Comment