Sweep up that mess!

I have a perhaps daunting task in front of me, and that’s to clean up a network block, and I don’t know what’s on it. So what’s a person to do? Well, I took a couple of minutes to write my own simple ping sweep.

Thankfully Microsoft made this nice and easy with the Test-Connection cmdlet. In the past you’d have to parse the output from our good old ping, and honestly nobody wants to spend their time doing that.

Throw in a loop and a test condition, and you’re almost all the way there. I decided that I wasn’t happy not knowing whether an IP was reachable or not, but not knowing who was at the receiving end, so I decided to use the .NET DNS class to do a lookup.  Now when this class doesn’t find a result it throws an ugly and unfriendly error message. For this reason you may have noticed that I set preferences for ErrorAction and WarnAction at the top of the script.

As written it won’t scan more than a class C, but you could pretty easily alter it to fit your needs.

And there you go! Simple ping sweeps.

$ErrorActionPreference ="SilentlyContinue"
 $WarningPreference = "SilentlyContinue"

$range = "192.168.42."
 $numpings =3

write-host "Please be patient.
 Based on the IP range entered, the script will take at least $(($lastip - $firstip) * ($numpings+1)) seconds to complete.
 Information that appears hereafter are hosts that are able to be reached"

 For ($ip=$firstip; $ip -lt $lastip; $ip++){
 if(Test-Connection $testip -Quiet -count $numpings ){
 write-host $testip -NoNewline
 $nsresult = [System.Net.Dns]::gethostentry($testip)
 if ($nsresult){
 write-host ", "$nsresult.HostName
 write-host ""
 #ping $testip -n 1
 if ($nsresult){$nsresult = $null}
 Clear-Variable testip

Write-Host "You found $count reachable addresses in this range"
 write-host "Fin!" -BackgroundColor Cyan -ForegroundColor Black



Leave a Reply

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

WordPress.com Logo

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

Google+ photo

You are commenting using your Google+ 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