PowerShell · Networking · Deep Dive
A single PowerShell script that discovers every device in a subnet, traces how each one reaches the internet, measures throughput between any two points and tells you, with evidence, where your network is slow. This post walks through how it works under the hood.
Free download: the script is available on GitHub at github.com/MSB365/Network-Scan-LAN.
It is free to use, modify and redistribute under the terms of the MIT License. Keep the copyright and license notice when you redistribute it.
Most network troubleshooting starts with the same handful of questions. What is actually connected to this subnet? Which of these devices should not be here? Why are Teams calls choppy in the afternoon? Is it the Wi-Fi, the firewall, the uplink between two switches or the internet line itself?
There are excellent tools for each of these questions on their own: an IP scanner, a traceroute or MTR, a speed test website, iperf. But you have to run them one by one, compare the outputs in your head and, more often than not, install something on a customer machine where you would rather not. Network-Scan-LAN started as a quick script to list the reachable addresses in a /24. Over a few iterations it grew into a complete diagnostic tool, still a single .ps1 file with no modules, no installers and no external binaries.
This article is the technical companion to the README. It explains the architecture, the protocols the script speaks on the wire and the heuristics it uses to decide what counts as a bottleneck, so you can trust the results, adapt the thresholds and extend the script yourself.
1. What the script does
You point the script at a subnet and it works through ten phases. Each phase prints a header, logs every individual step with a timestamp and a status, updates a two-level progress bar and finishes with an interim status line. You always see what it is doing and how far it has got.
At the end you get a console dashboard, an IP allocation map, a hop-by-hop path to the internet, a speed table with the narrowest point of the chain, a per-device connectivity table and two lists, one of bottlenecks and one of security findings, each finding with a recommendation. The same data is written to CSV, JSON and a self-contained HTML report with an interactive network map.
# the whole thing, with sensible defaults
.\Scan-Subnet.ps1 -Subnet 10.195.20.0/24
2. Architecture and the status framework
One state table, many phases
Internally, every address of the subnet becomes one [pscustomobject] in an ordered dictionary, created before the first packet is sent. Each phase enriches the same objects: Online and RTT from the ping sweep, MAC and Vendor from ARP, OpenPorts from the port scan, Lan statistics and Route from the path analysis, Findings and Risk from the assessment. The phases never pass data to each other directly. They only read from and write to this table.
$script:HostTable[$ip] = [pscustomobject]@{
IP = $ip; Online = $false; DetectedBy = ''; Ping = $false; RTT = $null; TTL = $null
Hostname = ''; NetBIOS = ''; Workgroup = ''; MAC = ''; Vendor = ''; Role = ''
OpenPorts = @(); Services = ''; DeviceType = ''; OS = ''
Web = [System.Collections.Generic.List[object]]::new()
Certificates = [System.Collections.Generic.List[object]]::new()
Findings = [System.Collections.Generic.List[object]]::new()
Lan = $null; HopCount = $null; PathHops = @(); Route = ''; SpeedDown = $null; SpeedUp = $null
}
This design has two practical advantages. Any phase can be skipped without breaking the following ones, because missing data is simply $null. And the exporters at the end only have to flatten one object per device.
Live status: four small building blocks
The requirement from the start was that the script always shows what it is doing and with which result. That is implemented with four functions:
Write-Statusprints one line in the form[mm:ss] [LEVEL] TAG message, with a color per level (INFO,OK,WARN,FAIL,--for skipped,>>>>for steps).Start-Phasedraws the phase header box, registers the phase in a list with its start time, updates the parent progress bar (Write-Progress -Id 0) and sets the console window title, so you can see the current phase even when the window is minimized.Complete-Phasestores duration, result and status (OK,Warn,Skipped), which later becomes the status overview table.Write-Scoreboardprints an interim status after every phase: devices online, devices without reply, open ports, findings and elapsed time.
Detailed per-item progress uses a child progress bar (-Id 1 -ParentId 0), so the console shows both "phase 4 of 10" and "host 37 of 112" at the same time. The whole run is captured with Start-Transcript into a log file inside a try/finally block, so the log is closed even when you press Ctrl+C.
3. Fast discovery: subnet math, ping and ARP
Subnet math without bit-twiddling pitfalls
IPv4 addresses are converted to integers by reversing the byte order of IPAddress.GetAddressBytes() (network order is big-endian, BitConverter is little-endian on x86/x64). PowerShell's bitwise operators on [uint32] have a few sign-related surprises, so the script avoids masks entirely and computes the network address with a modulo on [uint64]:
$size = [uint64][math]::Pow(2, 32 - $prefix)
$network = $ipInt - ($ipInt % $size)
# /31 and /32 have no network/broadcast address (RFC 3021)
if ($prefix -ge 31) { $first = $network; $last = $network + $size - 1 }
else { $first = $network + 1; $last = $network + $size - 2 }
Input is forgiving: http://10.195.20.0/24 works just as well as 10.195.20.0/24, which is handy when you copy a range from documentation or a ticket.
Async ping instead of Test-Connection
Test-Connection is sequential and slow on Windows PowerShell 5.1. The script uses System.Net.NetworkInformation.Ping.SendPingAsync() instead: it starts one task per address for a block of 64 addresses, then waits for all of them with a single Task.WaitAll(). A /24 is swept in about four rounds of the ping timeout, regardless of how many hosts are offline.
$jobs = foreach ($ip in $batch) {
$p = [System.Net.NetworkInformation.Ping]::new()
[pscustomobject]@{ IP = $ip; Ping = $p; Task = $p.SendPingAsync($ip, $PingTimeoutMs) }
}
[void][System.Threading.Tasks.Task]::WaitAll([System.Threading.Tasks.Task[]]@($jobs.Task))
Addresses without a reply get a second round (-PingRetries), which catches devices whose first ICMP packet was dropped while ARP resolution was still in progress. The TTL of each reply is stored. It is the basis for a rough OS hint later (˜64: Linux/Unix/embedded, ˜128: Windows, ˜255: network equipment).
Silent addresses are not printed as 200 identical lines. A small range compressor turns the list into .20–.63, .65–.99, .201. With -Detailed you get every address individually.
ARP: finding the devices that refuse to ping
Here is the part many scanners skip. Even if a host drops ICMP, your machine had to resolve its MAC address to send the ping, so the host is now in the ARP cache. The script reads Get-NetNeighbor (falling back to parsing arp -a) and marks every address that has a valid MAC but did not answer as online via ARP. Windows clients with the default firewall profile and many IoT devices show up only this way.
The MAC prefix (OUI) is looked up in a built-in list of common vendors. With -UpdateOuiDatabase, the official IEEE oui.csv (~35,000 entries) is downloaded once and cached in %LOCALAPPDATA%\SubnetScan. The script also checks the locally administered bit (bit 1 of the first octet). If it is set, the MAC is randomized, which is typical for phones and laptops with private Wi-Fi addresses, and the device is labeled accordingly instead of showing an empty vendor.
4. Parallel port scanning
The port scan is a TCP connect scan: the script opens a full TCP handshake and closes it again. It is less stealthy than a SYN scan, but it needs no raw sockets, no admin rights and no driver, and it produces exactly the result you care about: can an application connect to this port?
Speed comes from fanning out across hosts and ports at the same time. For a group of -HostParallel hosts (default 8) the script starts one TcpClient.ConnectAsync() for every host/port combination, 8 × 37 = 296 concurrent attempts, and waits once with a timeout:
$checks = foreach ($h in $grp) { foreach ($p in $Ports) {
$cl = [System.Net.Sockets.TcpClient]::new()
[pscustomobject]@{ Host = $h; Port = $p; Client = $cl; Task = $cl.ConnectAsync($h.IP, $p) }
} }
try { [void][System.Threading.Tasks.Task]::WaitAll([System.Threading.Tasks.Task[]]@($checks.Task), $PortTimeoutMs) } catch { }
# open = task completed successfully AND the socket is connected
A port counts as open only if the task finished successfully and the client reports Connected. Refused connections fault the task immediately; filtered ports simply time out. Hosts that answered neither ping nor ARP are skipped unless you pass -ScanAllHosts. With it, a device that only reveals itself through an open port is still detected and marked online via port.
5. Name resolution and raw NetBIOS
Reverse DNS runs as Dns.GetHostEntryAsync() for all online hosts in parallel. In many SMB networks, however, PTR records are missing or stale. NetBIOS fills that gap and has a bonus: the node status response contains the MAC address of the responding interface, even across routers where ARP cannot help.
Instead of calling nbtstat and parsing localized text output, the script builds the NBSTAT request itself and sends it over UDP 137:
# NBSTAT query: header + encoded name "*" + type 0x21 (NBSTAT) + class IN
$req = [byte[]](@(0x13,0x37, 0x00,0x00, 0x00,0x01, 0x00,0x00, 0x00,0x00, 0x00,0x00, 0x20) +
[Text.Encoding]::ASCII.GetBytes('CK' + ('A' * 30)) +
@(0x00, 0x00,0x21, 0x00,0x01))
NetBIOS uses "first-level encoding": every byte of the 16-byte name is split into two nibbles and each nibble is added to 'A'. The wildcard name * (0x2A) padded with 15 null bytes therefore becomes CK followed by thirty A. In the response, the name count sits at offset 56, followed by 18-byte entries (15 bytes name, 1 byte suffix, 2 bytes flags). The first unique name with suffix 0x00 is the computer name. The first group name (flag bit 0x80) with suffix 0x00 is the domain or workgroup. The six bytes after the last entry are the MAC address.
All queries are sent at once with one UdpClient per host, then collected with a single 1.5-second wait. Resolving names for 100 hosts takes about as long as resolving one.
6. Service detection: web, TLS and banners
Web interfaces
For every open web port the script requests / with redirects disabled and records the status code, Server header, Location and the page <title>. That is usually enough to identify a device: a printer's embedded web server, a firewall login page, an IIS default page, a NAS admin UI. If an HTTP port does not speak HTTP (common on 8080/8000), the script retries with HTTPS.
Lesson learned: HttpWebRequest uses the system proxy by default. On a corporate machine with a proxy, requests to internal RFC 1918 addresses were sent to the proxy and timed out. The script now sets $req.Proxy = $null for all device checks. Internal devices are always contacted directly, while the internet speed test keeps using the system proxy.
TLS certificates
Certificates are read with an SslStream on ports 443, 636, 993, 995, 5061, 5986 and 8443. The handshake explicitly allows TLS 1.0–1.3, because on Windows PowerShell 5.1 the .NET Framework defaults may not include TLS 1.2. The script records subject CN, issuer, expiry, whether it is self-signed (subject equals issuer) and the negotiated protocol. If a server still negotiates TLS 1.0 or 1.1, its best protocol is outdated, and that becomes a finding.
Because internal devices almost always use self-signed certificates, validation has to be disabled for detection. The callback is compiled as a tiny C# class instead of a PowerShell script block. Script block delegates need a PowerShell runspace on the calling thread, and TLS callbacks can fire on thread-pool threads where none exists, which leads to sporadic "no runspace available" errors.
public static class SubnetScanTrustAll {
public static bool Validate(object s, X509Certificate c, X509Chain ch, SslPolicyErrors e) { return true; }
public static readonly RemoteCertificateValidationCallback Callback = new RemoteCertificateValidationCallback(Validate);
}
Banners
SSH, FTP, SMTP, POP3, IMAP, VNC and Telnet announce themselves before the client sends anything. The script connects, reads the first line and keeps only printable ASCII bytes. Filtering happens on the raw bytes before decoding, otherwise Telnet's IAC negotiation bytes (0xFF …) turn into question marks. An SSH banner like SSH-2.0-OpenSSH_9.6p1 Ubuntu-3ubuntu13 overrides the TTL-based OS guess with something much more precise.
Device classification
Classification is a deliberately simple, ordered rule chain over open ports, vendor and role: the gateway is a router; Kerberos + LDAP is a domain controller; 9100/515/631 or a printer vendor is a printer; SIP ports or a VoIP vendor is a phone; RTSP or a camera vendor is a camera; and so on, down to "Linux / Unix" for SSH-only hosts and "Device with web interface". A VMware, Hyper-V, VirtualBox or QEMU MAC adds a (VM) suffix. The rules are easy to read and easy to extend for your own environment.
7. Parallel traceroute and hop statistics
This is where the script moves from inventory to diagnostics. The goal is to show which path traffic takes to the internet and where along that path latency, jitter or loss come from.
Sending all TTLs at once
A classic traceroute sends a probe with TTL 1, waits for the "time exceeded" answer, then TTL 2, and so on, which takes many seconds per target. Since every probe is independent, the script sends all TTLs from 1 to -MaxHops simultaneously as async pings with PingOptions(ttl, false):
Every reply with status TtlExpired (Windows) or TimeExceeded (Unix) reveals the router at that hop. The lowest TTL that returns Success is the hop count to the target; probes with higher TTLs simply reach the target too and are ignored. Some routers rate-limit ICMP "time exceeded" messages to one per second, and a burst of 30 probes would hit that limit. A second round re-probes only the TTLs that stayed silent, after a short pause.
Measuring each hop properly
Knowing which routers are on the path is only half of the picture. For latency, the script pings every discovered hop address directly, -PathProbes times (default 10), all hops in parallel per round. That yields minimum, average, maximum, loss and jitter per hop.
Some routers do not answer direct pings but do send "time exceeded". For those hops the script falls back to timing TTL-limited probes with a Stopwatch. This is necessary because on Windows, PingReply.RoundtripTime is reported as 0 for TtlExpired replies, so the reply object alone gives you no latency. Values measured this way are labeled (TTL) in the reports.
Jitter is calculated as the mean absolute difference between consecutive samples, the same idea as the interarrival jitter in RFC 3550 and what most VoIP tools report. Delta is the latency a hop adds compared to the previous answering hop, and that is the number that points to a slow link.
Every device, not just the scanning PC
The same measurement engine runs against every online device: ten pings per device, all devices in parallel per round. That gives you latency, jitter and loss for each IP, which quickly exposes a phone on bad Wi-Fi or a printer in power-save mode.
For the path of each device to the internet, the script distinguishes two cases. If the scanned subnet is directly attached, every device is one hop away and its route is LAN ? default gateway ? the measured internet path. If the subnet is routed, the script traces three sample devices (first, middle, last). If all samples share the same route, it is applied to all devices; otherwise every device is traced individually. The device route is then joined with the internet path at the deepest common router, producing a readable chain such as:
LAN ? GW 10.195.20.1 ? 5 hop(s) ? handover 195.186.0.73 ? Swisscom (Schweiz) AG · PoP ZRH
8. Path MTU, provider and PoP
Path MTU problems are a classic hidden cause of "some websites hang" or "VPN works, but file copies stall". The script sends pings with the Don't Fragment flag and performs a binary search on the payload size between 548 and 1472 bytes. The resulting MTU is the largest successful payload plus 28 bytes (20 bytes IPv4 header, 8 bytes ICMP header). A result of 1492 points to PPPoE, lower values to tunnels or VPNs.
$lo = 548; $hi = 1472
while ($hi - $lo -gt 1) {
$mid = [int][math]::Floor(($lo + $hi) / 2) # Floor, not [int] rounding: banker's rounding would loop forever
if (& $test $mid) { $lo = $mid } else { $hi = $mid }
}
return $lo + 28
The comment in that snippet is a real bug I hit along the way: PowerShell's [int] cast uses banker's rounding, so [int]1471.5 becomes 1472, $mid equals $hi, and the loop never terminates.
The public IP, provider and Internet PoP come from Cloudflare's speed test metadata endpoint, which returns the client IP, the ASN and organization and the three-letter code of the Cloudflare data center that served the request (ZRH, FRA, AMS …). If that endpoint is blocked, the script falls back to /cdn-cgi/trace. The PoP is a surprisingly useful sanity check: if an office in Zurich exits the internet in Frankfurt, a VPN, a security service edge or the provider's routing is sending traffic on a detour.
Each hop is also classified by its address range: Private (RFC 1918), CGNAT (100.64.0.0/10, RFC 6598) or Public. The first public hop is the handover point to the provider, and a CGNAT hop explains immediately why inbound VPN or port forwarding does not work.
9. The C# speed engine
Measuring throughput in pure PowerShell is a trap. A read loop in a script block is far too slow to saturate a gigabit link, and runspaces add complexity without solving the per-iteration overhead. The script therefore compiles a small C# class with Add-Type at startup. The hot loops run in compiled code, while PowerShell remains the orchestrator and the UI.
Download and upload against Cloudflare
The internet test opens -SpeedStreams parallel streams (default 4) for -SpeedTestSeconds per direction. Download repeatedly requests /__down?bytes=25000000 and discards the data. Upload is the interesting part. A naive ByteArrayContent only reports bytes when a whole request completes, which badly underestimates slow uplinks. Instead the script streams the body through a custom HttpContent that writes 64 KB chunks until the deadline and counts every chunk:
protected override async Task SerializeToStreamAsync(Stream stream, TransportContext context) {
long sent = 0;
while (sent < max && sw.Elapsed < deadline) {
await stream.WriteAsync(Payload, 0, Payload.Length);
sent += Payload.Length;
Interlocked.Add(ref LiveBytes, Payload.Length); // read by PowerShell for the live display
Interlocked.Add(ref Written, Payload.Length);
}
}
Two details make this work on Windows PowerShell 5.1. First, the request sets Headers.TransferEncodingChunked = true. Without it, the .NET Framework handler buffers a body of unknown length completely in memory to compute Content-Length, so the counter would race to the end before a single byte is on the wire. Second, ServicePointManager.DefaultConnectionLimit is raised from its .NET Framework default of 2 connections per host, otherwise four "parallel" streams would really be two.
The payload is random data generated once. Compressible patterns such as zeros could be compressed by WAN optimizers or VPN gateways and would inflate the result.
Live numbers and bufferbloat
While the compiled task runs, PowerShell polls a static LiveBytes counter every 200 ms, prints the current Mbit/s once per second and pings the reference target at the same time. That last part measures latency under load. Comparing it with the idle latency from the path analysis reveals bufferbloat: oversized buffers in the router or modem that fill up under load and add tens or hundreds of milliseconds to every packet. Bufferbloat is the most common reason why Teams calls become choppy the moment someone starts a large upload, and a plain speed test never shows it.
[00:24] [INFO] SPEED Internet ? Upload 93.8 Mbit/s live · so far 41.2 MB · latency under load 84 ms
[00:25] [INFO] SPEED Internet ? Upload 95.1 Mbit/s live · so far 52.5 MB · latency under load 91 ms
[00:26] [ OK ] SPEED Internet ? Upload: 94.6 Mbit/s (90 MB in 8 s, 4 streams) · latency under load avg 87.4 ms (+74.5 ms vs. idle)
Example console output. A 75 ms latency increase under upload load is a clear bufferbloat finding.
10. The speed partner protocol
The internet test tells you how fast the line is. It does not tell you whether the uplink between the second-floor switch and the core is the problem. For that you need a counterpart, because no device can measure throughput without something on the other end. Rather than depending on iperf, the script can act as its own counterpart:
# on the second device (other floor, VLAN or site)
.\Scan-Subnet.ps1 -SpeedServer
# on the scanning PC – partners in the scanned subnet are found automatically
.\Scan-Subnet.ps1 -Subnet 10.195.20.0/24 -SpeedPartners 10.195.30.10
The protocol on TCP 50201 is intentionally tiny and line-based, so it is easy to debug with a packet capture:
| Step | Direction | Content |
|---|---|---|
| 1 | Partner ? Scanner | SUBNETSCAN-SPEED/1\n (greeting, also used for auto-discovery during the port scan) |
| 2a | Scanner ? Partner | DOWN 8\n – the partner sends random data for 8 seconds, then half-closes its sending side |
| 2b | Scanner ? Partner | UP 8\n – the scanner sends for 8 seconds, then calls Shutdown(SocketShutdown.Send) |
| 3b | Partner ? Scanner | OK <bytes> <ms>\n – bytes actually received, so the upload result is not inflated by local socket buffers |
The half-close is the key detail for the upload direction. The scanner signals "no more data" without closing the socket, and the partner reads until end-of-stream and then reports what really arrived. Download and upload each use parallel connections, and the latency to the partner is measured during both tests.
On the partner side, the accept loop deliberately runs in PowerShell and polls TcpListener.Pending() every 100 ms instead of blocking in AcceptTcpClient(). A blocking .NET call would make Ctrl+C unresponsive. Each connection is handled in a compiled task, and log lines are passed back through a ConcurrentQueue, so the partner console shows every measurement live.
Placing partners in different segments turns a vague complaint into a measurement. 940 Mbit/s to a partner on the same switch and 310 Mbit/s to a partner one floor up identifies the uplink, not the client, as the bottleneck.
11. The bottleneck engine
Raw numbers are only useful if they are interpreted correctly, and traceroute output is notoriously easy to misread. The bottleneck engine encodes the rules an experienced engineer applies when reading an MTR report.
Rule 1: a latency jump only matters if it persists
Routers answer ICMP on their control plane, often with low priority. A hop that shows 40 ms while every following hop shows 12 ms is not slow. It just answers pings lazily, and forwarded traffic is unaffected. A jump is therefore only flagged if the minimum latency of all later hops stays above the previous level plus 70 % of the jump:
$delta = $avg - $prevAvg
$laterMin = ($later | ForEach-Object { $_.Stats.Avg } | Measure-Object -Minimum).Minimum
$persistent = $laterMin -ge ($prevAvg + 0.7 * $delta)
Thresholds then depend on where the jump happens. Inside your own network (private or CGNAT hops), 5 ms of persistent extra latency is already suspicious: think of an overloaded firewall doing deep inspection, a VPN or a radio link. On the access line from the last internal hop to the provider, 20 ms or more points to DSL interleaving, mobile or satellite access. Between public hops, jumps of 25 ms or more are reported only as information, because they are usually geography (long-distance links, undersea cables).
Rule 2: packet loss only matters if it continues to the target
The same logic applies to loss. Twenty percent loss on hop 5 with zero loss at the target is ICMP rate limiting, and the hop is annotated as harmless. Loss that starts at a hop and is still visible on every following hop is real and rated High, because that is where packets are actually dropped.
The full rule set
| Area | Condition | Severity |
|---|---|---|
| NIC | Internet download = 80 % of the NIC link speed | High |
| Path | Loss = 10 % starting at a hop and persisting to the target | High |
| Bufferbloat | Latency under load = +100 ms | High |
| NIC | Link speed = 100 Mbit/s (wired) | Medium |
| Gateway | First hop > 5 ms, persistent | Medium |
| Own network | Persistent jump = 5 ms between internal hops | Medium |
| Target | Loss = 1 % · jitter = 30 ms · RTT = 100 ms | Medium |
| Bufferbloat | Latency under load = +30 ms | Medium |
| LAN segment | Speed partner < 50 % of link speed | Medium |
| Device | Loss = 5 % | Medium |
| Access line | Persistent jump = 20 ms to the provider | Low |
| LAN segment | Download and upload differ by more than factor 2 (duplex mismatch?) | Low |
| Device | Average latency or jitter = 10 ms | Low |
| Path MTU | < 1500 bytes (Info), < 1400 bytes (Low) | Info / Low |
| Provider | CGNAT hop in the path | Info |
Every finding comes with a recommendation, for example "Enable Smart Queue Management (SQM, fq_codel/CAKE) or QoS on the router" for bufferbloat, or "Check intermediate switches, uplinks, cables, Wi-Fi bridges or firewalls between the segments" for a slow LAN segment. The thresholds live in one function, Invoke-BottleneckAnalysis, so you can adapt them to your own standards.
Teams check and the speed chain
Because many of the networks I look at run Microsoft Teams, the script compares the reference target with the commonly used Teams network targets: round-trip time below 100 ms, jitter below 30 ms and packet loss below 1 %. The check uses a public internet target, not the Microsoft edge itself, so treat it as an indicator for the local network and access line.
Finally, all measured capacities are lined up as a chain (NIC link, each LAN segment, internet download, internet upload) and the smallest value is reported as the narrowest point. In practice that one line often answers the original question.
Chain: NIC Ethernet 1,000 › LAN segment to 10.195.20.50 312 › Internet download 874 › Internet upload 95
Narrowest point: Internet upload with 94.6 Mbit/s (measured)
12. Building the network map
The HTML report contains a map of the path from the LAN to the internet targets, including branches for every speed partner. It is generated as plain SVG by PowerShell, with no JavaScript library and no external resources.
Every trace is converted into a chain of nodes with stable IDs: ip:<address> for answering hops, unk:<previous>:<ttl> for silent hops, P:<address> for speed partners. Chains are merged into a tree. A node is created only the first time its ID appears, so traces to 1.1.1.1 and 8.8.8.8 share the common prefix (gateway, core, provider) and branch where the paths diverge. Because edges are only created together with new nodes, routing loops cannot produce cycles.
The layout is a classic tidy-tree approach in a few lines. A depth-first pass assigns consecutive rows to leaf nodes, every parent is placed at the average row of its children, and the depth determines the column. Edges are cubic Bézier curves from the right edge of the parent to the left edge of the child. Each edge carries a label (the latency the hop adds, or ?312 ?941 for a partner) and a color: grey for normal, orange for noticeable, red for a bottleneck. The color comes from the bottleneck engine via the node ID, so the map and the findings table always agree.
The SVG uses width="100%" with a viewBox and a minimum width, so it scales down on smaller screens and becomes horizontally scrollable once it would get unreadable. Hovering over a node shows the full statistics as a native SVG tooltip.
13. Reports and change detection
Every run writes the following files into -OutputFolder:
- HTML report – a single self-contained file with KPI cards, IP allocation map, network map, bottlenecks, speed table, traceroute details, per-device connectivity, security findings and a filterable, sortable device table. It works offline and can be attached to a ticket as is.
- CSV – one row per device with a
;delimiter and UTF-8 encoding, so it opens correctly in Excel with European regional settings. - JSON – the complete device objects including web, certificate, banner and finding details, for further automation.
- Path CSV / JSON – one row per hop and target, plus speed results, Teams check, chain and bottlenecks.
- Log – the transcript of the full console session.
In addition, a baseline per subnet (baseline_<network>_<prefix>.json) stores IP, MAC, name, type and open ports of every device. The next scan compares against it and reports new devices, devices that are gone, and changes: a different MAC on the same IP (a swapped device or an IP conflict), a renamed host, or newly opened and closed ports. Run the script as a scheduled task with -NoOpen and you have a lightweight change monitor for a small network.
Security findings are generated alongside the bottlenecks: Telnet and VNC (High), FTP, PPTP, directly reachable databases, expired certificates and outdated TLS (Medium), RDP, WinRM over HTTP, NFS, unencrypted mail retrieval and HTTP-only admin interfaces (Low), plus informational hints such as active SMB (check SMBv1), raw print ports and duplicate MAC addresses.
14. PowerShell 5.1 vs. 7: lessons learned
The script runs on Windows PowerShell 5.1 and PowerShell 7+. Getting there required a few deliberate choices that are worth knowing if you write similar tools:
- C# 5 syntax in
Add-Type. Windows PowerShell 5.1 compiles inline C# with the .NET Framework compiler, so the embedded code avoids string interpolation,?.and expression-bodied members. On 5.1,System.Net.Httpmust be loaded and referenced explicitly; on 7 it is part of the default reference set. #Requiresplacement. If#Requiresis the first line, above the comment-based help,Get-Helpno longer finds the help block. It now sits directly below the help, andGet-Help .\Scan-Subnet.ps1 -Detailedshows all 27 parameters.- Reserved variable names. PowerShell variables are case-insensitive, so a harmless-looking
$pidcollides with the read-only automatic variable$PID. -Fileand arrays. When a script is started withpowershell.exe -File, an argument like1.1.1.1,8.8.8.8arrives as one string. List parameters are therefore split on commas, semicolons and whitespace.ifreturning an empty array.$x = if ($c) { … } else { @() }assigns$null, not an empty array, and@($null)then has one element. Wrapping the whole expression in@( … )avoids phantom entries.- Encoding. The file is saved as UTF-8 with BOM. Without the BOM, Windows PowerShell 5.1 reads the script in the ANSI code page and the box-drawing characters of the console UI turn into garbage.
- Proxy and TLS defaults. Device checks bypass the proxy explicitly; TLS 1.2 is enabled in
ServicePointManagerfor 5.1.
15. Limitations
It is worth being clear about what the script cannot see:
- Layer 2 is invisible. Switches do not decrement TTL, so they never appear in a traceroute. Speed partners in different segments let you isolate a slow switch or uplink by measurement; port-level topology would require LLDP or SNMP data from the switches.
- Paths of other devices are derived. Measurements are taken from the scanning PC. For devices in a directly attached subnet the script assumes they use the subnet's default gateway.
- Throughput needs a counterpart. Latency, jitter and loss are measured for every device; throughput only where a speed partner runs.
- ICMP-based metrics. Hosts or firewalls that drop ICMP show no latency, and routers that rate-limit ICMP can show loss on a single hop (which the engine detects and labels).
- The scanning PC matters. Wi-Fi, a VPN client or a 100 Mbit/s NIC limit every measurement, which is why the script flags these conditions itself.
16. Getting started
# 1. Download from GitHub and allow the script for this session
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
Unblock-File .\Scan-Subnet.ps1
# 2. First run – also downloads the full IEEE vendor database once
.\Scan-Subnet.ps1 -Subnet 192.168.1.0/24 -UpdateOuiDatabase
# 3. Thorough scan including devices behind ICMP firewalls
.\Scan-Subnet.ps1 -Subnet 192.168.1.0/24 -ScanAllHosts
# 4. Quick inventory without path analysis and speed tests
.\Scan-Subnet.ps1 -Subnet 192.168.1.0/24 -SkipPathAnalysis -SkipServiceDetection
# 5. Bottleneck hunt between two sites
# site B: .\Scan-Subnet.ps1 -SpeedServer
# site A:
.\Scan-Subnet.ps1 -Subnet 10.195.20.0/24 -SpeedPartners 10.20.0.15
# 6. Built-in help with all parameters
Get-Help .\Scan-Subnet.ps1 -Detailed
The README in the repository documents every parameter, every output file and every rule in detail.
Use responsibly. Only scan networks you own or are explicitly authorized to scan. Port scans and service detection can trigger IDS/IPS alerts, and the speed tests generate significant traffic for a few seconds, so run them outside business hours on busy links.
Download and license
Network-Scan-LAN is free and open source:
https://github.com/MSB365/Network-Scan-LAN
The script is published under the MIT License. You may use, copy, modify, merge, publish, distribute, sublicense and sell copies, privately and commercially, as long as the copyright notice and the license text are included in all copies or substantial portions of the software. The software is provided "as is", without warranty of any kind.
Issues, ideas and pull requests are welcome on GitHub, whether that is a new device classification rule, an additional security check or a threshold that fits your environment better. If the script helped you find a bottleneck, I would be glad to hear about it.
Happy scanning,
Drago
