PowerShell Test-Connection, Invoke-WebRequest, Invoke-RestMethod
Three built-in PowerShell cmdlets for network checks that return objects instead of text: Test-Connection (ping), Invoke-WebRequest (full HTTP response) and Invoke-RestMethod (JSON/XML parsed into objects). They exist in Windows PowerShell 5.1 and PowerShell 7 (Windows, Linux, macOS). Every request in the lab went only to a Docker API on 127.0.0.1:18209.
209.1 Why is it used?
- ping prints text; Test-Connection returns PingStatus objects you can filter, sort and use in if conditions.
- Invoke-WebRequest gives StatusCode, Headers, Content and Links as properties: health checks and downloads.
- Invoke-RestMethod turns API JSON into PSCustomObjects: no manual string parsing.
- Ideal for scripts: check a service, call an API, act on the result.
209.2 How it works
- Step 1
1.PowerShell sends GET through the Docker port 127.0.0.1:18209
- Step 2
2.Request reaches n209-api (192.168.229.10:8000)
- Step 3
3.Server returns status line + headers + body
- Step 4
4.Invoke-WebRequest: wraps it all in one response object (StatusCode 200, Headers, Content, Links)
- Step 5
5.Invoke-RestMethod: parses the JSON body into a PSCustomObject ($u.name -> Asha)
209.3 Invoke-WebRequest (PowerShell 5.1)
$base = 'http://127.0.0.1:18209'$r = Invoke-WebRequest "$base/" -UseBasicParsing$r.StatusCode$r.StatusDescription$r.Headers$r.Content$r.Links.hrefPS> $r.StatusCode200PS> $r.StatusDescriptionOKPS> $r.HeadersKey Value--- -----Content-Length 73Content-Type text/htmlDate Mon, 09 Nov 2026 13:24:40 GMTServer n209-api/1.0PS> $r.Content<html><body><h1>n209 lab</h1><a href="/api/users">users</a></body></html>PS> $r.Links.href/api/users- -UseBasicParsing skips the Internet Explorer DOM parsing (required on Server Core; deprecated in PowerShell 7).
- Headers is a dictionary; Content is the raw HTML; Links.href lists links on the page.
209.4 Invoke-RestMethod
Invoke-RestMethod "$base/api/users"$u = Invoke-RestMethod "$base/api/users/1"$u.name$u.GetType().FullName(Invoke-WebRequest "$base/api/users/1" -UseBasicParsing).ContentPS> Invoke-RestMethod http://127.0.0.1:18209/api/users id name email city-- ---- ----- ---- 1 Asha asha@example.com Pune 2 Ravi ravi@example.com IndorePS> $u.nameAshaPS> $u.GetType().FullNameSystem.Management.Automation.PSCustomObjectPS> (Invoke-WebRequest http://127.0.0.1:18209/api/users/1 -UseBasicParsing).Content{"id": 1, "name": "Asha", "email": "asha@example.com", "city": "Pune"}- A JSON array becomes a table: each JSON field is a column.
- The same data from Invoke-WebRequest .Content is just a JSON string.
209.5 POST, body and headers
$body = @{ name = 'Neha'; city = 'Delhi' } | ConvertTo-JsonInvoke-RestMethod -Method Post -Uri "$base/api/users" -Body $body -ContentType 'application/json'Invoke-RestMethod "$base/api/whoami" -Headers @{ 'X-Api-Key' = 'lab-key-123' 'X-Request-Id' = 'n209-7' }PS> $body{ "city": "Delhi", "name": "Neha"}PS> Invoke-RestMethod -Method Post -Uri http://127.0.0.1:18209/api/users -Body $body -ContentType 'application/json' city name id---- ---- --Delhi Neha 3PS> Invoke-RestMethod http://127.0.0.1:18209/api/whoami -Headers @{ 'X-Api-Key' = 'lab-key-123'; 'X-Request-Id' = 'n209-7' }apiKey requestId------ ---------lab-key-123 n209-7- ConvertTo-Json turns a hashtable into the JSON body; -ContentType 'application/json' tells the server what it is.
- The server returns the new user (id 3), again as an object.
- -Headers sends custom headers such as an API key; the lab API echoed both back.
209.6 Redirects, errors, timeouts and downloads
Invoke-RestMethod "$base/old"$x = Invoke-WebRequest "$base/old" -UseBasicParsing -MaximumRedirection 0 ` -ErrorVariable ev -ErrorAction SilentlyContinue$ev$x.StatusCode$x.Headers['Location']PS> Invoke-RestMethod http://127.0.0.1:18209/old id name email city-- ---- ----- ---- 1 Asha asha@example.com PunePS> $evInvoke-WebRequest : The maximum redirection count has been exceeded. To increase the number of redirectionsallowed, supply a higher value to the -MaximumRedirection parameter. + FullyQualifiedErrorId : MaximumRedirectExceeded,Microsoft.PowerShell.Commands.InvokeWebRequestCommandPS> $x.StatusCode302PS> $x.Headers['Location']/api/users/1try { Invoke-WebRequest "$base/missing" -UseBasicParsing} catch { $_.Exception.GetType().FullName $_.Exception.Response.StatusCode.value__}Measure-Command { try { Invoke-RestMethod "$base/slow" -TimeoutSec 2 } catch { $script:err = $_ }} | Select-Object TotalSeconds$err.Exception.MessageInvoke-RestMethod "$base/slow" -TimeoutSec 8PS> Invoke-WebRequest http://127.0.0.1:18209/missing -UseBasicParsingInvoke-WebRequest : {"error": "not found", "path": "/missing"}PS> try { ... } catch { $_.Exception.GetType().FullName; $_.Exception.Response.StatusCode.value__ }System.Net.WebException404PS> Measure-Command { ... -TimeoutSec 2 ... } | Select-Object TotalSeconds TotalSeconds------------ 2.0261383PS> $err.Exception.MessageThe operation has timed out.PS> Invoke-RestMethod http://127.0.0.1:18209/slow -TimeoutSec 8slow----TrueInvoke-WebRequest "$base/files/report.csv" -UseBasicParsing -OutFile "$out\report.csv"Get-Content "$out\report.csv"(Invoke-WebRequest "$base/files/report.csv" -UseBasicParsing -PassThru -OutFile "$out\report2.csv").StatusCodeid,name,city1,Asha,Pune2,Ravi,Indore200- Redirects are followed by default (max 5); -MaximumRedirection 0 stops at the 302, and the object still shows StatusCode and Location.
- In 5.1 a 404 throws System.Net.WebException; read the code from $_.Exception.Response.StatusCode.
- -TimeoutSec 2 failed after about 2 s on a 5 s endpoint; -TimeoutSec 8 succeeded.
- -OutFile writes the body to a file and returns nothing; add -PassThru to also get the response object.
209.7 Test-Connection
- Step 1
1.Admin PC (192.168.1.10) sends ICMP echo request
- Step 2
2.Through the router (192.168.1.1) to Server01 (192.168.2.20)
- Step 3
3.Server01 sends ICMP echo reply
- Step 4
4.Each reply becomes a PingStatus object: Address, ResponseTime, BufferSize
- Step 5
5.-Quiet returns only True/False for if conditions
Test-Connection 127.0.0.1 -Count 2 | Select-Object Address,ResponseTime,BufferSizeTest-Connection 127.0.0.1 -Count 2 -BufferSize 1000 | Select-Object Address,ResponseTime,BufferSizeTest-Connection 127.0.0.1 -Quietif (Test-Connection 127.0.0.1 -Count 1 -Quiet) { Invoke-RestMethod $base/api/users/1}PS> Test-Connection 127.0.0.1 -Count 2 | Select-Object Address,ResponseTime,BufferSize Address ResponseTime BufferSize------- ------------ ----------127.0.0.1 0 32PS> Test-Connection 127.0.0.1 -Count 2 -BufferSize 1000 | Select-Object Address,ResponseTime,BufferSize127.0.0.1 0 1000PS> Test-Connection 127.0.0.1 -QuietTruePS> if (Test-Connection 127.0.0.1 -Count 1 -Quiet) { Invoke-RestMethod http://127.0.0.1:18209/api/users/1 }id name email city-- ---- ----- ---- 1 Asha asha@example.com Pune- In 5.1 the Source column shows the PC name, so Select-Object kept only Address, ResponseTime and BufferSize.
- Loopback response time is 0 ms; -BufferSize 1000 sends 1000-byte pings (default 32).
- 5.1 uses -ComputerName (WMI: AsJob, ThrottleLimit, DCOM/WSMan); PowerShell 7 uses -TargetName.
209.8 PowerShell 7 only parameters
This PC has no pwsh, and the real checks for SkipCertificateCheck and TcpPort returned False on 5.1, so these examples come from Microsoft Learn.
(Get-Command Invoke-WebRequest).Parameters.ContainsKey('SkipCertificateCheck') # False on 5.1(Get-Command Test-Connection).Parameters.ContainsKey('TcpPort') # False on 5.1# PowerShell 7 only (Microsoft Learn):Invoke-RestMethod $uri -SkipCertificateCheckInvoke-WebRequest $uri -OutFile $f -ResumeInvoke-RestMethod $uri -StatusCodeVariable scInvoke-RestMethod $uri -SkipHttpErrorCheckInvoke-RestMethod $uri -NoProxyInvoke-RestMethod $uri -FollowRelLink -MaximumFollowRelLink 2Test-Connection bing.com -TCPPort 443 -Detailed -Count 4Test-Connection -TargetName www.google.com -Traceroute| Parameter | Cmdlet | What it does |
|---|---|---|
| -SkipCertificateCheck | IWR / IRM | Skips certificate validation (lab self-signed certs only) |
| -Resume | IWR / IRM | Continues a partial download (needs -OutFile) |
| -StatusCodeVariable, -ResponseHeadersVariable | IRM | Save status code / headers into variables |
| -SkipHttpErrorCheck | IWR / IRM | Error responses go down the pipeline instead of throwing |
| -FollowRelLink | IRM | Fetches next pages from the Link header |
| -MaximumRetryCount, -RetryIntervalSec | IWR / IRM | Retry on 304 and 400-599 |
| -TcpPort, -Traceroute, -Repeat, -MtuSize | Test-Connection | TCP port test, per-hop trace, continuous ping, path MTU |
209.9 Comparison: Invoke-WebRequest vs Invoke-RestMethod
| Point | Invoke-WebRequest | Invoke-RestMethod |
|---|---|---|
| Returns | Full response object | Parsed body (PSCustomObject / XML) |
| Status code / headers | Yes (.StatusCode, .Headers) | Only via -StatusCodeVariable / -ResponseHeadersVariable (7) |
| Best for | Downloads, status checks, HTML links | API data (JSON/XML) |
| 404/500 in 5.1 | WebException | WebException |
209.10 Common mistakes
- Thinking a failed ping means the server is down: firewalls often block ICMP while 443 works; test with -TcpPort (7) or Invoke-WebRequest.
- Parsing .Content by hand when Invoke-RestMethod gives objects directly.
- Forgetting try/catch: in 5.1 a 404 or 500 throws.
- Using -SkipCertificateCheck or -UseDefaultCredentials against untrusted servers.
209.11 Interview tips
- IWR = full response (StatusCode, Headers, Content) for downloads and status; IRM = JSON/XML to objects for API data.
- Test-Connection -Quiet returns True/False: perfect inside if.
- Ping fails but site works = ICMP blocked; check the real port.
- 5.1: -TimeoutSec, -UseBasicParsing; 7: -ConnectionTimeoutSeconds, -SkipHttpErrorCheck, -TcpPort.