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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.$_" | |
} | |
} |
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$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.$_"} | |
} | |
} | |
$vlan |
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 +