Ping Sweep Subnets with PowerShell
Sure, you can ping a subnet with this command:
1..255 | % {echo "192.0.2.$_"; ping -n 1 -w 100 192.0.2.$_ | Select-String ttl}
But if you’re going to run a ping sweep on more than a rare occasion it can be useful to have a script ready to go.
PS C:\Ping-Subnet.ps1
This script only works for /24 subnets! Modify this command as needed for other scenarios:
1..255 | % {echo 192.0.2.; ping -n 1 -w 192.0.2. | Select-String ttl}
Current IP Address:
192.0.2.25
[1.] Ping currently attached subnet
[2.] Enter /24 subnet to ping
[3.] Exit
Ping-Subnet.ps1
$Log = "results.txt"
Remove-Item -Force $Log -ErrorAction Ignore
$ipv4 = (Test-Connection -ComputerName (hostname) -Count 1).IPV4Address.IPAddressToString
function Print-Options() {
Write-Host "`n[1.] Ping currently attached subnet `n[2.] Enter /24 subnet to ping`n[3.] Exit"
$opt = Read-Host "`n`nChoose"
if([string]::IsNullOrEmpty($opt)) {
Write-Warning "Invalid choice selected. Exiting."
}
else{
return $opt
}
}
Write-Host "`nThis script only works for /24 subnets! Modify this command as needed for other scenarios:"
Write-Host "1..255 | % {echo "192.0.2.$_"; ping -n 1 -w 100 192.0.2.$_ | Select-String ttl}"
Write-Host "`nCurrent IP Address:`n"
$ipv4
$opt = Print-Options
switch($opt){
1{#
$ipv4Subnet = ($ipv4.split(".") | select -First 3) -join "."
}
2{#
$ipv4Subnet = Read-Host "`nEnter first 3 octets of /24 subnet. i.e. 10.1.1"
}
3{Exit}
Default{"Invalid choice selected."}
}
#Ping Subnet
1..254 | % {echo "$ipv4Subnet.$_"; ping -n 1 -w 100 "$ipv4Subnet.$_" | Select-String ttl | tee $Log -Append}
#Strip blank lines from log
(gc $Log) | ? { -not [String]::IsNullOrWhiteSpace($_) } | set-content $Log
#Remind user where login is located
Write-Host "Results are saved to $Log"
Further Reading:
https://www.sans.org/blog/sans-pen-test-cheat-sheet-powershell/
https://ss64.com/nt/ping.html