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 {
    $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    ping!    ping!    ping!        xxxxxxx.campus.ad.uvm.edu    ping!        xxxxxxx.uvm.edu    unreachable    ping!        xxxx.uvm.edu    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.

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.