Find Available IPs using PowerShell

I  still see engineers using ping to find available IP addresses and then changing the last octet to see if the next IP is available or not


As you can see if somebody needs to find 10 free IPs it may take a quiet sometime to find if  the IP address is available. Now let me show you two different ways you  can accomplish the same using automation.

The first way I would call it quick and dirty, because the script will give you the output on the screen and that is all you get.

1..254 | ForEach-Object {
if(!(Test-Connection 10.0.100.$_ -count 1 -Quiet)) {
Write-Output "IP Address Available 10.0.100.$_"
else {
Write-Output "IP Address in use 10.0.100.$_"

view raw


hosted with ❤ by GitHub

After you run that script you will get a similar Output on the screen


Now the problem with that approach is that you cant manipulate the output at all. For instance, if you wanted to only get IP address Available you can not do that and exporting the output to csv file would not give you the desired state.

Now let me show you the elegant way using PsCustomObject

$Vlan = 1..3 | ForEach-Object {
if(!(Test-Connection 10.0.100.$_ -count 1 -Quiet)) {
[pscustomobject]@{Name = "Available"; Value = "10.0.100.$_"}
else {
[pscustomobject]@{Name = "Not Available"; Value = "10.0.100.$_"}

view raw


hosted with ❤ by GitHub


Now lets look at the output


As you can see PowerShell treats it as an object meaning that it has methods and properties, this is available because  I used “PSCustomObject”. Now if you really need to get only the Available IP addresses,  execute the following command

$vlan | Where-Object {$_.Name -eq ‘Available’}


You can also  export to a csv using export-csv cmdlet

$vlan | Export-Csv C:\Location\test.csv


When using PSCustomObject keep in mind it only work on PowerShell version 3 +


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s