ping sweeping with FOR statements …

i just wanted to familiarize myself with the for statement in powershell by playing around with a few examples.  this one, i find particularly useful in situations where for example, i’m sitting in a lab and need to know what IPs are available.

back to what i was saying, to get familiar with the for statement, i thought i’d start off with what i know in cmd shell.  if you look at this this block below, you’ll see that i’m using the /L switch of the for statement to handle stepping through a sequence of numbers.

for /l %i in (1,1,255) do @ping -n 1 99.206.102.%i | find /i ": bytes=" > nul && @echo Successfully pinged 99.206.102.%i Successfully pinged 99.206.102.2 Successfully pinged 99.206.102.3 Successfully pinged 99.206.102.14 Successfully pinged 99.206.102.17

 
 

well, that worked out.  while the cmd shell has an IF statement, it doesn’t have a true if/then/else conditional statement.  you can simulate this in batch script… but you can’t do it with the cmd shell.  anyway, here’s the equivalent in powershell.  note though, that we can use if/then/else and can output results if the ping fails.  :)

for ($i = 1; $i -le 255; $i ++) {If ((Get-WmiObject win32_pingstatus -Filter "address='99.206.102.$i'").Statuscode -ne 0) {"Failed to ping 99.206.102.$i"} else {"Successfully pinged 99.206.102.$i"}}

Successfully pinged 99.206.102.1
Successfully pinged 99.206.102.2
Successfully pinged 99.206.102.3
Failed to ping 99.206.102.4
 
 
the first method was using the wmi class win32_pingstatus.  for the hell of it, here’s the same thing, using the .net ping method.  notice we have to initialize the ping object first, though.

$ping = New-Object System.Net.NetworkInformation.Ping

for ($i = 1; $i -le 255; $i ++) {If ($ping.Send("99.206.102.$i").Status -ne "Success") {"Failed to ping 99.206.102.$i"} else {"Successfully pinged 99.206.102.$i"}} Failed to ping 99.206.102.1 Failed to ping 99.206.102.2 Successfully pinged 99.206.102.3 Failed to ping 99.206.102.4

 
 
the for statements look pretty identical.  so, first cmd shell, then powershell:
for /l %<variable> in (<start>,<step>,<end>) DO <command_block>
 
for (<init>; <condition>; <repeat>) {<command_block>}

Comments

  1. Or, we can use the numeric range operator (..) instead:

    $ping = New-Object System.Net.NetworkInformation.Ping

    1..255 | % {$ip="99.206.102.$_";if ($ping.Send($ip).Status -ne "Success") {"Failed to ping $ip"} else {"Successfully pinged $ip"}}

    ReplyDelete
  2. thanks aleksandar... i totally forgot about that one. :)

    ReplyDelete

Post a Comment