PowerShell: Ping-Subnet

A couple a weeks ago I was hanging out in the PowerScripting Ustream waiting for the show to start. There were several of us caring on, when the interview subject Brandon Shell placed a call to scripting. He asked for a script to ping a subnet. There are many select-alive/ping-host scripts why write another one? The answer is simple pinging a target is easy, what Brandon was asking for was a fast way to generate the list of hosts. (Additionally, if you work with Active Directory then you can already see the usefulness in being able to ingest the subnets in sites and services as a parameter.) Shortly after Brandon made the request I opened my big mouth, and commented that the math was easy. The hard part is “threading”, as you know we can’t thread in PowerShell… but there are ways to perform concurrent operations. The PSJobs in V2 were purpose built for such a task. Unfortunately the *-job cmdlets use winrm as a backend, and require WS-MGMT to be installed/configured. As I was carrying on with this line of thought Brandon broke in, and informed me that the Get-WMIObject cmdlet in CTP3/V2 uses its own ‘backend’! He went on to inform me that all I needed was to tack on the –AsJob parameter… After a couple quick tests, I had a draft, and shortly thereafter a script!

I must say I am quite pleased with the results. As a test run I pinged one of my production LAN segments a /22 (1022 hosts) the script finished in under 50 seconds! I then scanned one of my deader segments a class C only 65 alive, execution time 14 seconds! I’m sure there is room for improvement, and the script can be made even faster (So have at it!). Additionally, the technique could be implied with any WMI task.

In the meantime enjoy,


~Glenn

4 thoughts on “PowerShell: Ping-Subnet”

  1. I don’t receive any output, which will be the form of executing the script?.
    PS>.pingsubnet.ps1 – 192.168.1.0 – 255.255.255.0
    how to pass parameters to the program?
    run script in windows xp sp3, all .netframework.
    please help me……

    Reply
    • No problem, In this case I didn’t write a script I wrote a function. The difference being a function must first be loaded before you can use it. Try the following;

      PS> . .pingsubnet.ps1
      PS> Ping-Subnet -IP 192.168.1.0 -Netmask 255.255.255.0

      note: That’s dot space path to script. This is known as dot sourcing.

      Reply
  2. another totally cheesy way to do this is to use Excel, and put in the top left cell:

    ping -n 1 192.168.0.1

    and drag the cell data down and produce 254 cells worth of data… then paste it into a command line. ugly but gets the job done in some cases.

    Reply

Leave a Reply