PowerShell – find a free IP

Since we don’t use DHCP in our server subnets, I frequently have to locate free IP addresses when deploying a server. I remembered reading a TechNet Magazine article by Don Jones that used the PowerShell PROCESS block and the Win32_PingStatus WMI class in a sample script.

I took that and rewrote the function a little:

function Ping-Address {
  PROCESS {
    $ping = 'unreachable'
    $formatstring = "{0,-15}  {1,-12} {2}"
    $queryString  = "SELECT * FROM Win32_PingStatus"
    $queryString += " WHERE Address = '$_' AND"
    $queryString += " ResolveAddressNames = $true"
    $results = Get-WmiObject -query $queryString
    
    foreach ($result in $results) {
      if ($results.StatusCode -eq 0) {
        $ping = 'ping!'
      }
    }
    $formatstring -f $_,$ping,$results.ProtocolAddressResolved
   }
}

I can then use this function like so:

PS Z:\> (14..20) | %{ '132.198.59.'+ $_.ToString()} | Ping-Address
132.198.59.14    ping!        132.198.59.14
132.198.59.15    ping!        132.198.59.15
132.198.59.16    ping!        xxxxxxx.campus.ad.uvm.edu
132.198.59.17    ping!        xxxxxxx.uvm.edu
132.198.59.18    unreachable
132.198.59.19    ping!        xxxx.uvm.edu
132.198.59.20    unreachable

I’ve already used it a bunch of times. I think I will probably grow this into a real script, taking the IP address range info as parameters. Another day.

Geoff
Sr. System Administrator at the University of Vermont

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.