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
$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
for /l %<variable> in (<start>,<step>,<end>) DO <command_block>for (<init>; <condition>; <repeat>) {<command_block>}
Or, we can use the numeric range operator (..) instead:
ReplyDelete$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"}}
thanks aleksandar... i totally forgot about that one. :)
ReplyDelete