Thursday 4 December 2008

Get-IPAddress2.ps1

# Get-IPAddress2.ps1
# Parses an address, returns a System.NET.IPAddress
if OK
# Uses tryparse (and therefore works with PSH v1)
# Thomas Lee
- tfl@psp.co.uk

$strings
= "10.1.1.100", "10.1", "fooey"

foreach( $string in $strings){
"Testing: `"{0}`"" -f $string
$address
= [System.Net.IPAddress]::tryparse($string,[ref] $ip1)
if ($address ){
"`"{0}`" `tis a valid IP address" -f [System.Net.IPAddress]::parse($string)
}
else {
"`"{0}`" `tis NOT a valid IP address" -f $string
}

}
This script produces the following output:

PS C:\foo> .\get-ipaddress2.ps1
Testing:
"10.1.1.100"
"10.1.1.100" is a valid IP address
Testing:
"10.1"
"10.0.0.1" is a valid IP address
Testing:
"fooey"
"fooey" is NOT a valid IP address

No comments: