Author Posts

May 19, 2013 at 11:30 am

I'm trying to do something that I thought should be simple.  Apparently, it's not as simple to me as I thought.  I'm creating a PowerShell script that will eventually use invoke-command.  Therefore, I want to make sure that a computer name was entered, and not an IP address.  This is what I have:

$test = '127.0.0.1'
If ($test -contains '...' ) {Write-Host 'IP Address Detected'}
else {Write-Host 'Computer Name Detected'}

I'm only using Write-Host for testing purposes.  I do not plan on using it in the final script 🙂

I'm open to any ideas for the best approach to detecting if the variable contains an IP address or not.

 

May 19, 2013 at 11:38 am

A minute after I posted the above, I found http://technet.microsoft.com/en-us/magazine/2007.11.powershell.aspx by our own Mr. Wonderful.  aka Don Jones 🙂

Based on that, this works.

$test = '192.168.1.50'
If ($test -match "\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}" ) {Write-Host 'IP Address Detected'}
else {Write-Host 'Computer Name Detected'}

Best way, maybe?  I'm not validating the data.  Just making sure the data looks right.

May 19, 2013 at 12:08 pm

You could simplify it to this

if ($test -notmatch "[a-z]"){Write-Host "IPAddress"}else{Write-Host "Computer Name"}

because an IP address shouldn't contain letters

May 19, 2013 at 12:17 pm

Richard,

I like that idea!  I wonder if I would run into that odd circumstance that has a computer name as '567'.  Doubtful, but I've seen many creating computer names in my time 🙂

May 19, 2013 at 1:06 pm

If you want to go the whole hog regular-expressions.info have more examples here. They have a regex that will go as far as matching valid ip's, whereas the example you gave would accept 999.999.999.999 as valid. Obviously that match is not a concern here, but i thought it was worth mentioning.

May 19, 2013 at 2:10 pm

Hi,

You can use this:

$ip = "192.168.0.1"
$IpCheck = ($ip -As [IPAddress]) -As [Bool]

if($IpCheck) {
"OK – IP"
} else {
"ERROR – NO IP"
}

 

 

July 13, 2017 at 5:06 pm

function FIND_NODE {

Write-host "Enter IP to Modify:(>" -NoNewline
$INPUT = Read-Host
$script:INPUT = $INPUT.Trim()
$Ipcheck = ($script:INPUT -AS [IPAddress]) -as [Bool]

if ($Ipcheck -ne "TRUE") {

Write-Host "$script:INPUT is not a valid IP"; FIND_NODE

}
}