Detecting if IP Address Entered

This topic contains 5 replies, has 4 voices, and was last updated by Profile photo of Kamil Tatar Kamil Tatar 4 years, 1 month ago.

  • Author
  • #6697
    Profile photo of Lery

    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 = ''
    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.


  • #6698
    Profile photo of Lery

    A minute after I posted the above, I found by our own Mr. Wonderful.  aka Don Jones 🙂

    Based on that, this works.

    $test = ''
    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.

  • #6700
    Profile photo of Richard Siddaway
    Richard Siddaway

    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

  • #6701
    Profile photo of Lery


    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 🙂

  • #6702
    Profile photo of Matt Tilford
    Matt Tilford

    If you want to go the whole hog 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.

  • #6703
    Profile photo of Kamil Tatar
    Kamil Tatar


    You can use this:

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

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



You must be logged in to reply to this topic.