none
testing ip address with .net in Powershell RRS feed

  • Question

  • I found the below a.net code, which returns true or false based the value of the $ip vary.  I'm having trouble actually using the returned values to perform either a continue or stop processing based on the result.  Can anyone assist?

    [ref]$a =$null

    [system.net.IPAddress]::tryparse($ip,$a)

    Thanks,

    Bryan


    • Edited by Bryan99 Saturday, June 7, 2014 11:32 AM
    Saturday, June 7, 2014 11:31 AM

Answers

  • What are you trying to do?

    $ip='192.168.1.1'
    
    
    Try{
        $ipaddress=[ipaddress]$ip
        # ip address good continue
    }
    Catch{
         Write-Host 'Address invalid' -fore red
    }
    

    Also this works

    if([ipaddress]::TryParse($ip,[ref]$null){
        #address good
    }else{
        # address bad
    }
    


    ¯\_(ツ)_/¯

    • Marked as answer by Bryan99 Sunday, June 8, 2014 9:52 AM
    Saturday, June 7, 2014 11:52 AM

All replies

  • What are you trying to do?

    $ip='192.168.1.1'
    
    
    Try{
        $ipaddress=[ipaddress]$ip
        # ip address good continue
    }
    Catch{
         Write-Host 'Address invalid' -fore red
    }
    

    Also this works

    if([ipaddress]::TryParse($ip,[ref]$null){
        #address good
    }else{
        # address bad
    }
    


    ¯\_(ツ)_/¯

    • Marked as answer by Bryan99 Sunday, June 8, 2014 9:52 AM
    Saturday, June 7, 2014 11:52 AM
  • I have a script to build a new network team in windows 2012 r2, but since Microsoft doesn't copy over the ip information already present on one of the nics, I have to pull the information and apply it to the new teamed nic.  I have gotten some errors, and though I think I have resolved that, wanted to test the ip before I built the team because if I don't the server will be offline, (no DHCP).  So if the IP's are bad, I want to exit the script, or jump to a section after the team building.
    Saturday, June 7, 2014 2:38 PM
  • What is a bad IP?  The test only tests the format of the IP.  It does not test if it is usable. It tests if the "string" is formatted correctly.  If the IP is on an adapter then it has already been tested.  You cannot set a bad IP on a NIC.  Try it and you will see the setting throws  an error.


    ¯\_(ツ)_/¯

    Saturday, June 7, 2014 3:35 PM
  • The script will be used in an automated server build, the server will have already been online with a correct ip. In early iterations of the script the wmi query to get the ip I would get unwanted data in the ip VARs,  although I believe I have this resolved, I wanted to test the VARs before I create the team and possibly have the server go offline.
    • Edited by Bryan99 Sunday, June 8, 2014 9:56 AM
    Sunday, June 8, 2014 9:52 AM