PowerShell as a Monitoring Probe
You do not need to buy anything, install anything, or file a purchase request to start testing your network from a Windows machine. Every Windows box you manage already ships with a complete, scriptable network test lab: PowerShell. Its built-in cmdlets (PowerShell's word for its small single-purpose commands) can ping a host and probe a TCP port. They can interrogate a specific DNS server and list live connections with the process that owns them. They can read interface counters and time a web page — all from the prompt you already have open.
This guide is a toolkit piece. First comes the tour: six cmdlets, each with its one-line superpower and a ready-to-paste example. Then comes the real payoff — turning one-liners into a proper probe. That is a small script that tests three things on a schedule and writes a timestamped result every time. It records failures instead of dying silently. It produces output a monitoring system (or a very simple alert wrapper) can actually consume. By the end you will have a starter probe kit and the habits that separate a useful probe from a script nobody trusts.
In this guide
- Six cmdlets, six superpowers
- From one-liners to a probe: build it step by step
- Scheduling it without surprises
- Making the results consumable
- Probe discipline, borrowed from the monitoring world
- Sweeping many machines with Invoke-Command
- A starter probe kit
- Where to go next
Six cmdlets, six superpowers
Each of these deserves a place in your muscle memory. Try every example against something real on your own network as you read — that is how the tour sticks.
Test-NetConnection — the Swiss Army knife
One cmdlet gives you three tests. Run it bare and it pings. Add -TraceRoute and it maps the path. Add -Port and it attempts a real TCP connection to a service. That last mode is the star. A ping only proves the machine is powered on and answering. A TCP connect to port 445 proves the file-sharing service is actually accepting connections. That is a far better health question, for reasons the guide on going beyond ICMP checks covers in depth.
Test-NetConnection fs01 -Port 445 ComputerName : fs01 RemoteAddress : 192.168.10.21 RemotePort : 445 InterfaceAlias : Ethernet SourceAddress : 192.168.20.57 TcpTestSucceeded : True
Read the last line first: TcpTestSucceeded : True means a full TCP handshake completed. The service answered the door, not just the doorbell. Note SourceAddress too: it tells you which of the machine's interfaces the test left through. That matters the moment a VPN adapter is in play.
Test-Connection — ping that speaks object
When you only need ping but you need it scriptable, this is the one. Its gift — and PowerShell's great gift to monitoring generally — is that it returns objects, not text. Classic tools print words you must chop apart with fragile parsing. PowerShell hands you named properties like ResponseTime that you can compare, average, and log directly.
# Average round-trip time over four pings, no text parsing Test-Connection 192.168.10.1 -Count 4 | Measure-Object -Property ResponseTime -Average # One clean boolean for scripts: reachable or not Test-Connection 192.168.10.1 -Count 2 -Quiet True
-Quiet collapses the whole affair into True or False, perfect inside an if. (Parameter names vary slightly across PowerShell editions; the patterns here use the edition preinstalled on Windows.)
Resolve-DnsName — ask a specific server, on purpose
Ordinary name lookups ask whatever resolver the machine happens to be configured with, cache included. Resolve-DnsName lets you point the question at an exact server with -Server. The option -DnsOnly skips the local cache and hosts file so you hear the server's answer, not a memory of it. That makes this the one-liner for hunting split-brain DNS. That is the maddening situation where two resolvers give different answers for the same name and only some users suffer:
Resolve-DnsName portal.company.example -Type A -DnsOnly -Server 192.168.10.5 Resolve-DnsName portal.company.example -Type A -DnsOnly -Server 192.168.10.6
Run both, compare the answers. If they differ, you have just found in ten seconds what tail-chasing a "the portal is down for some people" ticket can burn an afternoon on.
Get-NetTCPConnection — netstat with a brain
This lists live TCP connections as objects — state, addresses, ports, and crucially OwningProcess. You can join that to Get-Process to answer the eternal question: who is making all these connections?
Get-NetTCPConnection -State Established |
Group-Object -Property OwningProcess |
Sort-Object Count -Descending |
Select-Object -First 5 Count,
@{n='Process';e={(Get-Process -Id $_.Name).ProcessName}}
Top five connection hogs, by name, in one pipeline. The full story of using the endpoint as a sensor — connection tables, retransmit statistics, SMB health — lives in monitoring from the host. This cmdlet is your entry ticket.
Get-NetAdapter and Get-NetAdapterStatistics — the NIC, in script form
Link state and speed without opening a single control panel:
Get-NetAdapter | Select-Object Name, Status, LinkSpeed Name Status LinkSpeed ---- ------ --------- Ethernet Up 1 Gbps
If LinkSpeed says 100 Mbps on what should be a gigabit port, you have found a bad cable or a negotiation problem. That is before anyone graphs anything. Get-NetAdapterStatistics adds the running byte and packet counters — totals since boot. So like all counters they become rates only when you read twice and divide by the time between reads.
Invoke-WebRequest — the stopwatch HTTP check
For a web application, the health question is "does the page come back, and how fast?" A stopwatch object gives you clean millisecond timing:
$sw = [System.Diagnostics.Stopwatch]::StartNew()
$r = Invoke-WebRequest "https://portal.company.example" -UseBasicParsing -TimeoutSec 15
$sw.Stop()
"Status {0} in {1} ms" -f $r.StatusCode, $sw.ElapsedMilliseconds
Status 200 in 412 ms
That 412 ms is the whole trip as this machine experienced it — DNS, TCP, TLS, and the server thinking. That is exactly what a user at this machine would feel. It is a basic timing pattern, not a full waterfall, and for a probe that is precisely enough.
From one-liners to a probe: build it step by step
A probe (also called a synthetic check) is just a test that runs on a schedule and records its result every single time — success or failure. That last clause is where most homemade scripts fall down, so let us build one properly. The plan is to test three things that matter: DNS answering, the file server's SMB port, and the intranet portal's response time. Then append one timestamped line per check to a CSV file.
Step one, a tiny helper so every check writes results the same way:
$log = "C:\Probes\net-probe-results.csv"
$stamp = Get-Date -Format "yyyy-MM-dd HH:mm:ss"
function Write-Result($check, $result, $ms, $detail) {
"$stamp,$check,$result,$ms,$detail" | Add-Content -Path $log
}
Step two, the checks — each wrapped in try/catch so a failure produces a FAILURE record instead of a crash. Note the -ErrorAction Stop: it turns soft errors into catchable ones, which is what makes the pattern reliable:
# Check 1: DNS, against a specific server
try {
$t = Measure-Command {
Resolve-DnsName fs01.company.example -Server 192.168.10.5 `
-DnsOnly -ErrorAction Stop | Out-Null
}
Write-Result "dns-dc1" "OK" ([int]$t.TotalMilliseconds) ""
} catch {
Write-Result "dns-dc1" "FAILURE" "" ($_.Exception.Message -replace ',',';')
}
# Check 2: the file server's SMB port
$tnc = Test-NetConnection fs01 -Port 445 -WarningAction SilentlyContinue
if ($tnc.TcpTestSucceeded) { Write-Result "smb-fs01" "OK" "" "" }
else { Write-Result "smb-fs01" "FAILURE" "" "tcp 445 refused or timed out" }
# Check 3: the portal, with timing
try {
$sw = [System.Diagnostics.Stopwatch]::StartNew()
Invoke-WebRequest "https://portal.company.example" -UseBasicParsing `
-TimeoutSec 15 -ErrorAction Stop | Out-Null
$sw.Stop()
Write-Result "http-portal" "OK" $sw.ElapsedMilliseconds ""
} catch {
Write-Result "http-portal" "FAILURE" "" ($_.Exception.Message -replace ',',';')
}
After a few runs the log reads like a tiny flight recorder, one line per check per run:
yyyy-mm-dd 09:35:02,dns-dc1,OK,4, yyyy-mm-dd 09:35:02,smb-fs01,OK,, yyyy-mm-dd 09:35:03,http-portal,OK,412, yyyy-mm-dd 09:40:02,dns-dc1,OK,5, yyyy-mm-dd 09:40:04,smb-fs01,FAILURE,,tcp 445 refused or timed out
The anti-pattern to design against: the script that dies quietly. An unhandled error stops the run, nothing gets written, and the log simply has a gap. That looks exactly like "everything was fine." A probe that only records success is a smoke detector with no battery. The rule: every check writes a line every run, and a failed test is a result to record, never an excuse to stop. (The small -replace ',',';' keeps error text from smuggling commas into your CSV columns.)
Scheduling it without surprises
Save the script as C:\Probes\net-probe.ps1 and hand it to Task Scheduler, the Windows service that runs things on a clock. Create a task with a daily trigger. Then in the trigger's advanced settings repeat it every 5 minutes for a duration of 1 day. That is the standard recipe for "run this every five minutes, forever." The action is:
Program: powershell.exe Arguments: -NoProfile -ExecutionPolicy Bypass -File "C:\Probes\net-probe.ps1"
Three Task Scheduler realities catch nearly everyone once:
- "Run whether user is logged on or not." Select this, or your probe only runs while someone is sitting at the machine — which quietly turns it into a business-hours probe. Choosing it means the task needs stored credentials. Use a dedicated low-privilege account for probes rather than your own admin account. That way, a password change on your account does not silently kill monitoring.
- The working-directory gotcha. Scheduled tasks do not start in your script's folder; they start in a system directory. Any relative path in the script (
.\results.csv) lands somewhere surprising or fails. Use absolute paths everywhere, or set the task's "Start in" field — absolute paths are the sturdier habit. - Test it as the task, not as you. Right-click the task and choose Run, then check that the log grew. Your interactive session has your profile, your drive mappings, and your permissions; the task has none of them. The five minutes you spend proving the task itself works saves the classic "it worked when I ran it by hand" mystery.
Making the results consumable
A probe nobody reads is a diary, not monitoring. Three ways to make the results reach a human, in ascending order of maturity.
Let your monitoring system ingest the file. The CSV format above is deliberately boring: timestamp, check name, OK or FAILURE, a number, a detail. Most monitoring platforms can tail or ingest a file like this, turning your homemade checks into first-class alerts and graphs alongside everything else.
A threshold-then-alert wrapper. Until then, a few lines at the end of the probe can send email when something crosses a line. Add one crucial refinement: alert on the second consecutive failure, not the first. That way, a single lost packet does not page anyone at 3 AM. A one-line state file is enough to remember the previous run:
$state = "C:\Probes\portal-fail-streak.txt"
if ($portalFailed) {
$streak = if (Test-Path $state) { [int](Get-Content $state) + 1 } else { 1 }
Set-Content $state $streak
if ($streak -eq 2) {
Send-MailMessage -To "netops@company.example" -From "probe@company.example" `
-Subject "Portal check failing from $env:COMPUTERNAME" -SmtpServer mail01
}
} elseif (Test-Path $state) { Remove-Item $state }
Write failures to the Windows event log. The event log is the output channel with the best plumbing. It is durable and timestamped. And — the real prize — centralized event collection will forward it off the machine automatically. So probe failures from fifty workstations arrive in one place. Setup is a one-time elevated command, then one call in your catch blocks:
# One-time setup (elevated): New-EventLog -LogName Application -Source "NetProbe" # In the probe, on failure: Write-EventLog -LogName Application -Source "NetProbe" -EntryType Warning ` -EventId 100 -Message "smb-fs01 FAILURE: tcp 445 refused or timed out"
How to collect and actually use those events centrally is the subject of Windows event logs that reveal network problems.
One housekeeping habit, whichever channel you choose: a probe that appends a few lines every five minutes writes hundreds of thousands of lines a year. A forgotten log eventually fills a disk. At that point your monitoring script becomes the outage. Add a trim step to the probe itself (keep the newest few thousand lines, drop the rest) or a weekly scheduled cleanup. Decide up front how much history you actually need. A week of five-minute results answers almost every "when did this start?" question you will ever ask of it.
Probe discipline, borrowed from the monitoring world
Professional synthetic monitoring has a small rulebook, and hand-rolled probes deserve the same discipline. Three rules carry most of the value.
Frequency: enough to notice, not enough to annoy. Every five minutes is plenty for most service checks; every minute for something truly critical. Resist the urge to hammer a production server every ten seconds from a dozen workstations. You would be manufacturing the load you are supposed to be watching. And stagger the start times a little if many machines run the same probe, or you build a tiny synchronized stampede.
Confirmation before alarm. Networks flicker. One failed check is a data point; two or three consecutive failures are an event. You already saw the streak-file pattern above. That is a miniature version of the confirmation logic real monitoring systems apply. It is also the difference between an alert channel people trust and one they mute.
Vantage honesty. A probe can only report what the network looks like from where it stands. A check running on the server itself proves the service is up; it proves nothing about whether users can reach it across the building. The genuinely clever move is running your probe on an ordinary workstation in a user VLAN. It crosses the same switches, the same firewall rules, and the same DNS path your users do. So it sees what users see — often the whole point. The guides on designing synthetic probes and probe placement take both ideas much further.
Sweeping many machines with Invoke-Command
Sometimes the question is not "is the server up" but "can everyone reach it?" Invoke-Command fans a check out across machines and gathers the answers. Here is the same port test, run from ten vantage points at once:
Invoke-Command -ComputerName pc-sales-01, pc-sales-02, pc-warehouse-07 -ScriptBlock {
Test-NetConnection fs01 -Port 445 -WarningAction SilentlyContinue |
Select-Object TcpTestSucceeded
} | Select-Object PSComputerName, TcpTestSucceeded
PSComputerName TcpTestSucceeded
-------------- ----------------
pc-sales-01 True
pc-sales-02 True
pc-warehouse-07 False
One warehouse machine cannot reach the file server while sales can — in three lines you have localized a problem to a segment. The catch: this rides on WinRM (Windows Remote Management). WinRM must be enabled on the target machines, allowed through their firewalls, and used by an account with rights on them. That is the same remote-access territory — and the same do-it-safely checklist — covered in the remote-access section of WMI and CIM for network data. So set it up once and both toolkits benefit.
A starter probe kit
Six checks that earn their keep on almost any network. Start with the two or three that map to your most-heard complaints:
| Check | Cmdlet pattern | Schedule | What it catches |
|---|---|---|---|
| File server answering SMB | Test-NetConnection fs01 -Port 445 | Every 5 min | Service down, firewall rule change, server half-alive |
| Portal response time | Invoke-WebRequest + stopwatch | Every 5 min | Slow app, certificate and site errors, creeping degradation |
| DNS from each resolver | Resolve-DnsName -Server per DC | Every 5 min | One dead or lying resolver, split-brain answers |
| Gateway round-trip trend | Test-Connection avg ResponseTime | Every 1–5 min | LAN congestion, duplex trouble, flaky uplink |
| Internet reachability | Test-Connection -Quiet to two outside anchors | Every 5 min | ISP or edge trouble (two anchors so one site's bad day is not "the internet") |
| VPN concentrator port | Test-NetConnection vpn -Port 443 | Every 5 min | Remote-access outage before the phones light up |
Where to go next
You now hold the whole arc. You have cmdlets that answer real health questions and a probe pattern that never fails silently. You have a scheduler configuration that survives logoffs and password changes, and outputs that flow toward a human. Hand-rolled probes are genuinely worth building. They teach you exactly what a monitoring check is, and they cover the odd corners no product ships a check for. Their honest cost is maintenance: every script, credential, and threshold is yours to remember, on every machine that runs one. That is the gap a monitoring platform fills — running the checks at scale, on schedule, with the alerting discipline built in. Your PowerShell skills remain the tool for the custom cases and the quick investigations. For the rest of the host-side story, the Windows-Side Network Monitoring guides continue with counters, WMI, event logs, and the art of correlating it all.
Put this into practice with SysPeep Monitor
You just scripted checks for whether it is up, the port is answering, and it is fast enough. SysPeep Monitor runs those checks all day, at scale, without the script maintenance. It auto-discovers your devices and collects health and performance data over WMI, SNMP, and SSH. It applies thresholds and alert rules designed to page you only when it matters. Keep your PowerShell kit for the custom corners, and let the free trial handle the routine.
Download Free TrialLearn About SysPeep