This is a brief post containing a a piece of code that I use to do a ping sweep and resolve host names in PowerShell on a /24 subnet.
A /24 subnet refers to the last octet (segment of numbers) in an IP, and it ranges from 1 to 254.
This means that if you provide 100.100.100 to the $FirstThreeOctets variable, you’ll end up pinging every IP between 100.100.100.1 and 100.100.100.254.
If you want more in-depth info than this on subnets and IPs, you might want to read this.
The PowerShell code to do a ping sweep
Just replace the xxx.xxx.xxx with the first three octets in the range you want to do a ping sweep on, paste the code in PowerShell and run it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | $FirstThreeOctets = "xxx.xxx.xxx" 1..254 | ForEach-Object { $IP = "$FirstThreeOctets.$_" if (Test-Connection -Count 1 -ComputerName $IP -Quiet) { try { $HostName = Resolve-DnsName -Name $IP -ErrorAction Stop | Select-Object -ExpandProperty NameHost -ErrorAction Stop Write-Host "$IP - $HostName" } catch { $HostName = "<Could not resolve hostname>" Write-Host "$IP - " -NoNewline Write-Host "$HostName" -Fore red } } } |
This is how the output looks:
That’s it, that’s the post.
I just needed to do a ping sweep in my LAN to see if there’s stuff without DHCP reservations by comparing the output of the above command with the decoded config backup from my router.
If you want some SQL Server related PowerShell goodness, check out my post on automating SQL Server instance installation with PowerShell.