PS: Validating User Input for an IP Address or Subnet Mask

PS: Validating User Input for an IP Address or Subnet Mask

Okay in one of my scripts I needed to incorporate user input of an IP address and to validate the input as valid IPv4 address. Take a look at the snippet below

 <#IP Validation Pattern#>
$IPPattern = '^(?:(?: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]?)$'

<#User Input of IP #>
Write-Host "Please Enter IP: " -ForegroundColor Yellow -NoNewline
<#Input Loop Until Validation meets pattern#>
do {
<# Set IP address var #>
$IPADR = Read-Host
$ok = $IPADR -match $IPPattern
if ($ok -eq $false) {
<# Error Message and Prompt to enter an IP #>
Write-Warning ("'{0}' is not an IP address." -f $IPADR)
write-host -fore Yellow "Please Enter IP: " -NoNewline
}
<#Condition#>
} until ( $ok )

 

 

Advertisements