Calling REST APIs and Web Requests
Call REST APIs from PowerShell with Invoke-RestMethod: query strings, bearer tokens, JSON bodies, status codes, pagination, retries, timeouts and file downloads.
By The Dark DebuggerUpdated 24 min read
This article teaches you to call HTTP APIs from PowerShell: reading data, sending JSON, handling status
codes, paging through results, retrying, setting timeouts and downloading files. It ends with a script
that syncs a CSV file into an inventory API. You should know JSON from
CSV, JSON, and XML and try/catch from
Error Handling. It opens the Automation in Practice section;
Remoting, Background Jobs, and Parallelism comes next.
Why this matters
Your CMDB, monitoring tool, ticket system and cloud provider all have HTTP APIs. Fixing forty inventory records by hand takes an afternoon; a script does it every night. The call itself is one cmdlet. What decides whether the script can run unattended is the rest: the 503 at 2 AM, the expired token, the second page nobody read, and the server that never answers.
A practice API to follow along
Every example runs against a small local API, so you can reproduce the output and break things safely.
It is a Python 3 script (standard library only; I used Python 3.12) that keeps seven servers in memory.
Save it as inventory-api.py:
#!/usr/bin/env python3
# inventory-api.py - an in-memory practice API. Run: python3 inventory-api.py 8765
import json, os, sys, time
from http.server import ThreadingHTTPServer, BaseHTTPRequestHandler
from urllib.parse import urlparse, parse_qs
TOKEN, HITS = os.environ.get("INVENTORY_API_TOKEN", "dev-token-123"), {}
ROWS = """web-01 web prod 10.20.1.11 ubuntu-24.04 active
web-02 web prod 10.20.1.12 ubuntu-24.04 active
db-01 db prod 10.20.2.21 ubuntu-22.04 active
db-02 db prod 10.20.2.22 ubuntu-22.04 active
cache-01 cache prod 10.20.3.31 ubuntu-24.04 active
web-stg-01 web staging 10.30.1.11 ubuntu-24.04 active
db-stg-01 db staging 10.30.2.21 ubuntu-22.04 maintenance"""
SERVERS = {r.split()[0]: dict(zip("name role environment ip os status".split(), r.split())) for r in ROWS.splitlines()}
class Api(BaseHTTPRequestHandler):
def send(self, code, data, headers={}, ctype="application/json; charset=utf-8"):
body = data if isinstance(data, bytes) else json.dumps(data, indent=2).encode()
self.send_response(code)
for k, v in {"Content-Type": ctype, "Content-Length": len(body), **headers}.items():
self.send_header(k, str(v))
self.end_headers()
self.wfile.write(body)
def log_message(self, fmt, *args): # one line per request
sys.stderr.write("%s %s %s\n" % (time.strftime("%H:%M:%S"), self.requestline, args[1]))
def do_GET(self):
url = urlparse(self.path)
p, name, q = url.path, url.path.rsplit("/", 1)[-1], {k: v[0] for k, v in parse_qs(url.query).items()}
if p == "/health":
return self.send(200, {"status": "ok", "version": "1.4.2"})
if p == "/api/echo": # returns the query parameters it received
return self.send(200, q)
if p == "/api/servers": # paged list with an optional ?environment= filter
items = [s for s in SERVERS.values() if q.get("environment") in (None, s["environment"])]
page, per = int(q.get("page", 1)), int(q.get("per_page", 3))
pages = -(-len(items) // per)
link = '<http://%s%s?page=%d&per_page=%d>; rel="next"' % (self.headers["Host"], p, page + 1, per)
return self.send(200, {"page": page, "total_pages": pages, "total": len(items),
"items": items[(page - 1) * per:page * per]}, {"Link": link} if page < pages else {})
if p.startswith("/api/servers/"):
if name in SERVERS:
return self.send(200, SERVERS[name])
return self.send(404, {"error": "server '%s' not found" % name})
if p == "/api/flaky": # the first ?fail=N calls to this exact URL fail with ?code= (503 or 429)
HITS[self.path] = HITS.get(self.path, 0) + 1
code = int(q.get("code", 503))
if HITS[self.path] <= int(q.get("fail", 2)):
return self.send(code, {"error": "try again later"}, {"Retry-After": 3} if code == 429 else {})
return self.send(200, {"status": "ok", "attempt": HITS[self.path]})
if p == "/api/slow":
time.sleep(float(q.get("seconds", 5)))
return self.send(200, {"status": "finally"})
if p.startswith("/files/") and os.path.isfile("files/" + name):
return self.send(200, open("files/" + name, "rb").read(), ctype="text/plain")
self.send(404, {"error": "no route for " + p})
def do_POST(self): # POST /api/servers creates, PUT /api/servers/NAME merges, POST /api/echo echoes
raw = self.rfile.read(int(self.headers.get("Content-Length", 0))).decode(errors="replace")
ctype, name = self.headers.get("Content-Type", ""), self.path.rsplit("/", 1)[-1]
if self.path == "/api/echo":
return self.send(200, {"contentType": ctype, "body": raw})
if self.headers.get("Authorization") != "Bearer " + TOKEN:
return self.send(401, {"error": "missing or invalid bearer token"})
if not ctype.startswith("application/json"):
return self.send(415, {"error": "Content-Type must be application/json", "received": ctype, "body": raw})
try:
data = json.loads(raw)
except ValueError:
return self.send(400, {"error": "body is not valid JSON", "body": raw})
if self.command == "POST":
SERVERS[data["name"]] = data
return self.send(201, data, {"Location": "/api/servers/" + data["name"]})
if name not in SERVERS:
return self.send(404, {"error": "server '%s' not found" % name})
SERVERS[name].update(data)
self.send(200, SERVERS[name])
do_PUT = do_POST
port = int(sys.argv[1]) if len(sys.argv) > 1 else 8765
print("inventory API listening on http://localhost:%d" % port, file=sys.stderr)
ThreadingHTTPServer(("127.0.0.1", port), Api).serve_forever()Start it in a second terminal and leave it running; restarting it brings back the original data. It logs one line per request, which I quote when the server's view proves a point.
python3 inventory-api.py 8765inventory API listening on http://localhost:8765Reads are public; POST and PUT need the bearer token dev-token-123. /api/flaky fails a few
times before it succeeds, /api/slow takes as long as you ask, and /files/ serves downloads. Create
the two files for the download section from PowerShell, in the same folder:
New-Item -ItemType Directory -Path ./files -Force | Out-Null
@'
name,role,environment,ip
web-01,web,prod,10.20.1.11
web-02,web,prod,10.20.1.12
db-01,db,prod,10.20.2.21
'@ | Set-Content -Path ./files/nightly-export.csv
$hash = (Get-FileHash -Path ./files/nightly-export.csv -Algorithm SHA256).Hash.ToLower()
"$hash nightly-export.csv" | Set-Content -Path ./files/nightly-export.csv.sha256Invoke-RestMethod and Invoke-WebRequest
Invoke-RestMethod sends the request, reads the body and turns JSON into objects:
$api = 'http://localhost:8765'
$server = Invoke-RestMethod -Uri "$api/api/servers/web-01"
$servername : web-01
role : web
environment : prod
ip : 10.20.1.11
os : ubuntu-24.04
status : activeInvoke-WebRequest returns the whole response instead: status code, headers, and the body as a string
you convert yourself. It is the tool for downloads and for seeing exactly what came back:
$response = Invoke-WebRequest -Uri "$api/api/servers/web-01"
$response.StatusCode
$response.Headers['Content-Type']
($response.Content | ConvertFrom-Json).ip200
application/json; charset=utf-8
10.20.1.11Query strings
For a GET, pass parameters as a hashtable to -Body and PowerShell builds the query string:
$result = Invoke-RestMethod -Uri "$api/api/servers" -Body @{ environment = 'staging'; per_page = 10 }
$result.items | Format-Table name, role, ip, statusname role ip status
---- ---- -- ------
web-stg-01 web 10.30.1.11 active
db-stg-01 db 10.30.2.21 maintenanceBuilding the URL with string interpolation breaks as soon as a value contains a character that means
something in a URL. /api/echo returns the parameters it received:
$team = 'R&D Ops'
(Invoke-RestMethod -Uri "$api/api/echo?team=$team").team
(Invoke-RestMethod -Uri "$api/api/echo?team=$([uri]::EscapeDataString($team))").team
(Invoke-RestMethod -Uri "$api/api/echo" -Body @{ team = $team }).teamR
R&D Ops
R&D OpsThe first request went out as ?team=R&D%20Ops, which is team=R plus a second parameter named
D Ops. No error, just wrong data. Escape every interpolated value with [uri]::EscapeDataString(),
or let -Body do it.
Headers and authentication tokens
Most APIs want a token in an Authorization: Bearer ... header, passed as a hashtable to -Headers.
The token comes from an environment variable or a secret store, never from the script file, which gets
committed and copied around. Setting it at the prompt is fine for a practice token; in production the
CI system or scheduled task sets it. Our API merges whatever fields a PUT sends:
$env:INVENTORY_API_TOKEN = 'dev-token-123'
$headers = @{ Authorization = "Bearer $env:INVENTORY_API_TOKEN" }
$change = @{ status = 'maintenance' } | ConvertTo-Json
(Invoke-RestMethod -Method Put -Uri "$api/api/servers/db-02" -Headers $headers -ContentType 'application/json' -Body $change).statusmaintenanceWithout -Headers $headers, the same call fails with the API's 401 body,
"error": "missing or invalid bearer token". PowerShell 7 also has -Authentication Bearer -Token,
which takes the token as a SecureString. Over plain HTTP it refuses to send it: The cmdlet cannot protect plain text secrets sent over unencrypted connections. Against a real HTTPS API it just works;
for a localhost practice server, -AllowUnencryptedAuthentication lets the call through. Avoid the
?api_key= style when a header is an option: our server log prints every request line, and a token
in the URL would be sitting in it.
Sending JSON with POST
Build the body as an ordered hashtable, convert it with ConvertTo-Json, and set -ContentType.
Splatting keeps the call readable, and PowerShell 7 can capture the status code and response headers:
$newServer = [ordered]@{
name = 'web-03'; role = 'web'; environment = 'prod'
ip = '10.20.1.13'; os = 'ubuntu-24.04'; status = 'active'
}
$params = @{
Method = 'Post'
Uri = "$api/api/servers"
Headers = $headers
ContentType = 'application/json'
Body = $newServer | ConvertTo-Json
}
$created = Invoke-RestMethod @params -StatusCodeVariable code -ResponseHeadersVariable respHeaders
"$code $($respHeaders['Location'])"
$created | Format-Table name, role, ip, status201 /api/servers/web-03
name role ip status
---- ---- -- ------
web-03 web 10.20.1.13 active201 Created plus a Location header is the textbook answer to a POST. Whether PUT merges fields,
as ours does, or replaces the whole record depends on the API; check before sending a partial PUT.
ConvertTo-Json serialises only two levels of nesting by default, which bites request bodies:
$payload = [ordered]@{
name = 'web-04'
monitoring = @{ checks = @( @{ type = 'http'; path = '/health' } ) }
}
$payload | ConvertTo-Json -Compress
$payload | ConvertTo-Json -Compress -Depth 10WARNING: Resulting JSON is truncated as serialization has exceeded the set depth of 2.
{"name":"web-04","monitoring":{"checks":["System.Collections.Hashtable"]}}
{"name":"web-04","monitoring":{"checks":[{"type":"http","path":"/health"}]}}Without -Depth, the API would store the string System.Collections.Hashtable as a health check.
ConvertTo-Json also unwraps a one-element array: piping @( [ordered]@{ name = 'web-05' } ) gave
{"name":"web-05"}, while ConvertTo-Json -InputObject on the same array gave [{"name":"web-05"}].
Use -Depth 10 on every body and -InputObject when the API expects an array;
CSV, JSON, and XML covers both in detail.
Status codes and errors
| Code | Meaning | What the script should do |
|---|---|---|
| 2xx | Success (201 created, 204 no body) | Carry on |
| 400, 415 | Malformed request or wrong Content-Type | Fix the request; retrying will not help |
| 401, 403 | Bad, expired or insufficient credentials | Stop and alert |
| 404 | Does not exist | Often a normal answer ("not in inventory") |
| 409 | Conflict, for example a duplicate | Treat as "already done" or update instead |
| 429, 5xx | Rate limited or server failure | Retry with backoff, honouring Retry-After |
Any status of 400 or above makes Invoke-RestMethod raise an error, and PowerShell 7 shows the body:
Invoke-RestMethod -Uri "$api/api/servers/web-99"Invoke-RestMethod:
{
"error": "server \u0027web-99\u0027 not found"
}(\u0027 is an apostrophe; PowerShell 7 re-formats the JSON for display.) The error stops the
statement, not the script. try/catch catches it even without -ErrorAction Stop, but a script
with no try carries on: in a two-line test script, the line after the failed call still ran and
$server was $null. In a sync script, that can mean "the server is missing, create it again".
Handle errors deliberately, one of two ways. When an error status is a normal answer (404 for "not in
the inventory"), PowerShell 7's -SkipHttpErrorCheck -StatusCodeVariable code returns the error body
as the result and puts the status in $code, so you can switch on it; Exercise 1 builds a lookup
function that way. Network failures still throw, because there is no status to hand you: with
-SkipHttpErrorCheck against a port with nothing listening, the call failed with Connection refused.
When failure is the exception rather than the rule, use try/catch and read the status and body
from the error record:
foreach ($uri in "$api/api/servers/web-99", 'http://localhost:8769/health') {
try {
$server = Invoke-RestMethod -Uri $uri -ErrorAction Stop
}
catch {
$status = [int]$_.Exception.Response.StatusCode # 0 when no HTTP response arrived
if ($status) { "HTTP {0}: {1}" -f $status, ($_.ErrorDetails.Message | ConvertFrom-Json).error }
else { "No HTTP response: $($_.Exception.Message)" }
}
}HTTP 404: server 'web-99' not found
No HTTP response: Connection refused (localhost:8769)A status of 0 means nothing answered, which is the case worth retrying; a 404 is not.
Windows PowerShell 5.1 differences
Everything above ran on PowerShell 7.6. I ran the same calls with Windows PowerShell 5.1 against the same API; these are the differences that matter:
| PowerShell 7.6 | Windows PowerShell 5.1 | |
|---|---|---|
-SkipHttpErrorCheck, -StatusCodeVariable | Available | Parameter not found; use try/catch |
-MaximumRetryCount, -RetryIntervalSec | Available | Parameter not found; write a retry loop |
| Exception for HTTP errors | HttpResponseException | WebException; [int]$_.Exception.Response.StatusCode and $_.ErrorDetails.Message work on both |
ConvertTo-Json past -Depth | Truncates and warns | Truncates silently |
ConvertTo-Json -AsArray | Available | Parameter not found; use -InputObject |
| String request bodies | Sent as UTF-8 | Non-ASCII mangled unless the content type says charset=utf-8 |
Invoke-WebRequest without -UseBasicParsing | Works (parsing is always basic) | Tried to prompt, which fails in a non-interactive session |
10 MB download with -OutFile | Not measured | 7.7 s with the progress bar, 0.0 s (rounded) with $ProgressPreference = 'SilentlyContinue' |
The encoding row silently corrupts data. With plain application/json, 5.1 sent the ü in a legacy
single-byte encoding:
$body = [ordered]@{ name = 'web-zrh-01'; site = 'Zürich' } | ConvertTo-Json -Compress
(Invoke-RestMethod -Method Post -Uri "$api/api/echo" -ContentType 'application/json' -Body $body).body
(Invoke-RestMethod -Method Post -Uri "$api/api/echo" -ContentType 'application/json; charset=utf-8' -Body $body).body{"name":"web-zrh-01","site":"Z�rich"}
{"name":"web-zrh-01","site":"Zürich"}PowerShell 7 sent Zürich intact with plain application/json. If a script must run on 5.1, put
; charset=utf-8 in every JSON content type and turn off the progress bar before downloads.
Pagination
APIs return long lists in pages; ours sends three servers per page unless you ask for more. Read only page one and your script works in testing and quietly ignores most of production. Loop until the API says there are no more pages, assigning the loop to a variable to collect what it emits:
$page = 1
$allServers = do {
$response = Invoke-RestMethod -Uri "$api/api/servers" -Body @{ page = $page; per_page = 3 }
$response.items
$page++
} while ($page -le $response.total_pages)
"$($allServers.Count) servers in $($page - 1) requests"8 servers in 3 requestsEight, because we created web-03 earlier. APIs signal the end in different ways (a page count like
ours, a next URL or cursor, an empty page); use whatever yours documents. When the next URL comes in
a Link response header, as ours does, PowerShell 7's -FollowRelLink follows it for you: against
our API it returned the 3 pages with all 8 servers in one call.
Retries
APIs answer 503 during deploys and 429 when you are too fast. PowerShell 7 can retry for you:
/api/flaky?fail=2 fails twice, and with -MaximumRetryCount 3 -RetryIntervalSec 2 -Verbose the call
logged Retrying after interval of 2 seconds. Status code for previous attempt: ServiceUnavailable
twice and returned ok on attempt 3. Testing further turned up two surprises. The built-in retry
retries a 404, which will never succeed, and it does not retry a refused connection, which is what a
restarting service looks like:
try { Invoke-RestMethod -Uri "$api/api/servers/web-99" -MaximumRetryCount 2 -RetryIntervalSec 1 } catch { $_.Exception.Message }
try { Invoke-RestMethod -Uri 'http://localhost:8769/health' -MaximumRetryCount 2 -RetryIntervalSec 1 -Verbose } catch { $_.Exception.Message }Response status code does not indicate success: 404 (Not Found).
VERBOSE: WebRequest: v1.1 GET http://localhost:8769/health
Connection refused (localhost:8769)The server log showed the 404 requested three times, a second apart; the refused connection got a
single WebRequest line and no retry. It does honour Retry-After: with code=429 our API sends
Retry-After: 3, and a call with -MaximumRetryCount 2 -RetryIntervalSec 1, timed with
Measure-Command, returned ok after 3.0 seconds, not 1. To retry only what is worth retrying (429, 5xx, no response), back off exponentially, or run on 5.1,
write a small wrapper:
function Invoke-ApiWithRetry {
[CmdletBinding()]
param(
[Parameter(Mandatory)] [hashtable] $Request,
[int] $MaxAttempts = 4,
[int] $BaseDelaySec = 1
)
for ($attempt = 1; ; $attempt++) {
try {
return Invoke-RestMethod @Request -ErrorAction Stop
}
catch {
# 0 means no HTTP response at all: DNS failure, refused connection, timeout
$status = [int]$_.Exception.Response.StatusCode
$retryable = $status -eq 0 -or $status -eq 429 -or $status -ge 500
if (-not $retryable -or $attempt -ge $MaxAttempts) { throw }
$delay = $BaseDelaySec * [math]::Pow(2, $attempt - 1)
Write-Warning "Attempt $attempt failed (HTTP $status), retrying in $delay s"
Start-Sleep -Seconds $delay
}
}
}
Invoke-ApiWithRetry -Request @{ Uri = "$api/api/flaky?key=c&fail=3" }
try { Invoke-ApiWithRetry -Request @{ Uri = "$api/api/servers/web-99" } } catch { "Not retried: $($_.Exception.Message)" }WARNING: Attempt 1 failed (HTTP 503), retrying in 1 s
WARNING: Attempt 2 failed (HTTP 503), retrying in 2 s
WARNING: Attempt 3 failed (HTTP 503), retrying in 4 s
status attempt
------ -------
ok 4
Not retried: Response status code does not indicate success: 404 (Not Found).Only retry requests that are safe to repeat. GET and PUT are; a POST that timed out may already
have created the record, and retrying it creates a duplicate.
Timeouts
Neither version gives up on a slow server by default. I called /api/slow?seconds=130 with no timeout
set: PowerShell 7.6 returned the result after 130.3 seconds and Windows PowerShell 5.1 after 132.2. A
scheduled script talking to a hung server hangs with it, so set -TimeoutSec on every call:
try {
Invoke-RestMethod -Uri "$api/api/slow?seconds=10" -TimeoutSec 3
}
catch {
$_.Exception.GetType().FullName
$_.Exception.Message
}System.Threading.Tasks.TaskCanceledException
The request was canceled due to the configured HttpClient.Timeout of 3 seconds elapsing.In PowerShell 7.6, -TimeoutSec is an alias of -ConnectionTimeoutSeconds. The separate
-OperationTimeoutSeconds only covers reading a response that has started: with
-OperationTimeoutSeconds 2, /api/slow?seconds=6 returned normally after 6.0 seconds. Use
-TimeoutSec, set comfortably above the API's normal response time.
Downloading files
Invoke-WebRequest -OutFile streams to disk. When a checksum is published, check it before you use the
file; Get-FileHash returns uppercase hex, and -eq ignores case:
New-Item -ItemType Directory -Path ./downloads -Force | Out-Null
Invoke-WebRequest -Uri "$api/files/nightly-export.csv" -OutFile ./downloads/nightly-export.csv
$expected = (Invoke-RestMethod -Uri "$api/files/nightly-export.csv.sha256").Split(' ')[0]
$actual = (Get-FileHash -Path ./downloads/nightly-export.csv -Algorithm SHA256).Hash
$expected
$actual
$expected -eq $actual923f71a6d477cdc5a412f19b9328ad72823ca4a8dc0daa7a943d94533c3ee3e5
923F71A6D477CDC5A412F19B9328AD72823CA4A8DC0DAA7A943D94533C3EE3E5
TrueYour hash differs if you created the CSV on Windows (CRLF line endings); the comparison still works.
Where you'll use this
Inventory and CMDB sync (the example below), health checks after a deployment that fail the pipeline
when /health is not ok, chat and incident notifications (a JSON POST to a webhook URL, which you
treat as a secret), opening tickets with the API's error body when a scheduled check fails, and cloud or
SaaS administration when a module does not cover the one call you need.
A complete example: syncing a CSV into the inventory API
A CSV in source control lists the servers that should exist. A nightly job makes the API match it. It
must not create duplicates, must never delete on its own, must show what it would do first, and must
exit with a code the scheduler can act on. desired-servers.csv:
name,role,environment,ip,os,status
web-01,web,prod,10.20.1.11,ubuntu-24.04,active
web-02,web,prod,10.20.1.12,ubuntu-24.04,active
web-03,web,prod,10.20.1.13,ubuntu-24.04,active
db-01,db,prod,10.20.2.21,ubuntu-24.04,active
db-02,db,prod,10.20.2.22,ubuntu-22.04,active
web-stg-01,web,staging,10.30.1.11,ubuntu-24.04,active
db-stg-01,db,staging,10.30.2.21,ubuntu-22.04,activeSync-Inventory.ps1:
#Requires -Version 7.0
# Sync-Inventory.ps1 - makes the inventory API match a CSV of desired servers.
[CmdletBinding(SupportsShouldProcess)]
param(
[Parameter(Mandatory)] [string] $DesiredStatePath,
[string] $ApiBase = 'http://localhost:8765'
)
$ErrorActionPreference = 'Stop'
if (-not $env:INVENTORY_API_TOKEN) { throw 'INVENTORY_API_TOKEN is not set.' }
# Shared settings. Reads are safe to retry; writes are not.
$auth = @{ Headers = @{ Authorization = "Bearer $env:INVENTORY_API_TOKEN" }; TimeoutSec = 10 }
$read = $auth + @{ MaximumRetryCount = 3; RetryIntervalSec = 2 }
$write = $auth + @{ ContentType = 'application/json' }
# 1. Refuse to start if the API is not healthy.
try {
if ((Invoke-RestMethod -Uri "$ApiBase/health" @read).status -ne 'ok') { throw 'status is not ok' }
}
catch {
Write-Error "Inventory API at $ApiBase is not healthy: $($_.Exception.Message)" -ErrorAction Continue
exit 2
}
# 2. Fetch every page of servers the API knows about.
$byName = @{}
$page = 1
do {
$response = Invoke-RestMethod -Uri "$ApiBase/api/servers" -Body @{ page = $page; per_page = 50 } @read
foreach ($server in $response.items) { $byName[$server.name] = $server }
$page++
} while ($page -le $response.total_pages)
# 3. Compare every desired server with the API and fix the differences.
$desired = Import-Csv -Path $DesiredStatePath
$report = foreach ($want in $desired) {
$have = $byName[$want.name]
$diff = [ordered]@{}
foreach ($field in 'role', 'environment', 'ip', 'os', 'status') {
if ($have.$field -ne $want.$field) { $diff[$field] = $want.$field }
}
$action = if (-not $have) { 'create' } elseif ($diff.Count) { 'update' } else { 'none' }
$detail = if ($have) { ($diff.Keys | ForEach-Object { '{0}: {1} -> {2}' -f $_, $have.$_, $diff[$_] }) -join '; ' } else { 'new server' }
$outcome = if ($action -eq 'none') { 'in sync' } else { 'skipped' }
if ($action -ne 'none' -and $PSCmdlet.ShouldProcess($want.name, $action)) {
try {
if ($action -eq 'create') {
$diff.Insert(0, 'name', $want.name)
$null = Invoke-RestMethod -Method Post -Uri "$ApiBase/api/servers" -Body ($diff | ConvertTo-Json) @write
}
else {
$null = Invoke-RestMethod -Method Put -Uri "$ApiBase/api/servers/$($want.name)" -Body ($diff | ConvertTo-Json) @write
}
$outcome = 'done'
}
catch {
$outcome = 'FAILED: HTTP {0}' -f [int]$_.Exception.Response.StatusCode
}
}
[pscustomobject]@{ Server = $want.name; Action = $action; Outcome = $outcome; Detail = $detail }
}
# Servers the CSV does not mention are reported, never deleted.
$report += $byName.Keys | Where-Object { $_ -notin $desired.name } | Sort-Object | ForEach-Object {
[pscustomobject]@{ Server = $_; Action = 'unmanaged'; Outcome = 'left alone'; Detail = 'not in CSV' }
}
$report | Format-Table -AutoSize
$failed = @($report | Where-Object Outcome -like 'FAILED*').Count
'{0} servers checked, {1} changed, {2} failed' -f $report.Count, @($report | Where-Object Outcome -eq 'done').Count, $failed
if ($failed) { exit 1 }It applies the earlier sections: a health gate exits with code 2 before touching anything; reads get
-MaximumRetryCount but writes do not, so a timed-out POST is never repeated; every call has a
timeout and the token comes from the environment; every page is fetched before comparing; only changed
fields are sent; SupportsShouldProcess gives you -WhatIf (see
Functions and Advanced Functions); and servers missing
from the CSV are reported, never deleted, because a truncated CSV should not empty the inventory.
Restart the practice API. With -WhatIf, the script printed one line per planned change, such as
What if: Performing the operation "create" on target "web-03"., and changed nothing. Then run it
for real:
$env:INVENTORY_API_TOKEN = 'dev-token-123'
./Sync-Inventory.ps1 -DesiredStatePath ./desired-servers.csv
$LASTEXITCODEServer Action Outcome Detail
------ ------ ------- ------
web-01 none in sync
web-02 none in sync
web-03 create done new server
db-01 update done os: ubuntu-22.04 -> ubuntu-24.04
db-02 none in sync
web-stg-01 none in sync
db-stg-01 update done status: maintenance -> active
cache-01 unmanaged left alone not in CSV
8 servers checked, 3 changed, 0 failed
0The API log showed one health check, one page read, one POST and two PUTs, and a second run
reported 8 servers checked, 0 changed, 0 failed. Now the failure paths: someone puts db-02 into
maintenance by hand (with the valid $headers from earlier), and the job's token has expired:
$null = Invoke-RestMethod -Method Put -Uri "$api/api/servers/db-02" -Headers $headers -ContentType 'application/json' -Body '{"status":"maintenance"}'
$env:INVENTORY_API_TOKEN = 'expired-token'
./Sync-Inventory.ps1 -DesiredStatePath ./desired-servers.csv
$LASTEXITCODE[…]
db-02 update FAILED: HTTP 401 status: maintenance -> active
[…]
8 servers checked, 0 changed, 1 failed
1Pointed at a port with nothing listening (-ApiBase http://localhost:8769), the health gate printed
Inventory API at http://localhost:8769 is not healthy: Connection refused (localhost:8769) and the
exit code was 2. Exit codes 0, 1 and 2 let the scheduler tell "in sync", "fix the data" and "the API
is down" apart. Real-World PowerShell Scripts covers
scheduling scripts like this one.
Common mistakes
Sending a hashtable as the body
-Body accepts a hashtable, so this looks right:
Invoke-RestMethod -Method Post -Uri "$api/api/servers" -Headers $headers -Body @{ name = "web-05"; role = "web" }Invoke-RestMethod:
{
"error": "Content-Type must be application/json",
"received": "application/x-www-form-urlencoded",
"body": "role=web\u0026name=web-05"
}For anything but GET, a hashtable is sent as an HTML form. Adding -ContentType 'application/json'
alone does not help: the body stays form-encoded and the API answered 400, body is not valid JSON.
Fix: -Body ($data | ConvertTo-Json -Depth 10) with -ContentType 'application/json'.
Porting a 5.1 catch block to PowerShell 7
Older scripts read the error body from the response stream. PowerShell 7's response object has no such method:
try { Invoke-RestMethod -Uri "$api/api/servers/web-99" } catch { $reader = [System.IO.StreamReader]::new($_.Exception.Response.GetResponseStream()) }InvalidOperation: Method invocation failed because [System.Net.Http.HttpResponseMessage] does not contain a method named 'GetResponseStream'.Fix: $_.ErrorDetails.Message for the body and [int]$_.Exception.Response.StatusCode for the status.
Both work on 5.1 and 7.
Summary
Invoke-RestMethodreturns parsed objects;Invoke-WebRequestreturns the raw response and is the tool for downloads.- Pass
GETparameters as a hashtable to-Body, or wrap each value in[uri]::EscapeDataString(). - Tokens come from the environment or a secret store and go in an
Authorizationheader, never in the URL or the script. - Send JSON with
ConvertTo-Json -Depth 10and-ContentType 'application/json'(plus; charset=utf-8on 5.1); use-InputObjectfor arrays. - HTTP errors stop the statement, not the script. Use
-SkipHttpErrorCheckwith-StatusCodeVariablewhen an error code is a normal answer, ortry/catchwith[int]$_.Exception.Response.StatusCodeand$_.ErrorDetails.Message. - Fetch every page. Built-in retries also retry 404s and skip refused connections, so wrap calls that
must retry only 429, 5xx and network failures, and never blindly retry a
POST. - Always set
-TimeoutSecin unattended scripts; neither version times out on its own.
Exercises
Restart the practice API before each exercise so the data matches.
Write Get-ServerSummary that takes a server name and prints NAME (IP) is STATUS, or
NAME is not in the inventory on a 404. Any other status should throw. Do it without try/catch, and
test it with cache-01 and web-42.
Show Solution
function Get-ServerSummary {
param([Parameter(Mandatory)] [string] $Name)
$server = Invoke-RestMethod -Uri "http://localhost:8765/api/servers/$Name" -SkipHttpErrorCheck -StatusCodeVariable code
switch ($code) {
200 { '{0} ({1}) is {2}' -f $server.name, $server.ip, $server.status }
404 { "$Name is not in the inventory" }
default { throw "Inventory API returned HTTP $code for $Name" }
}
}
Get-ServerSummary -Name cache-01
Get-ServerSummary -Name web-42cache-01 (10.20.3.31) is active
web-42 is not in the inventoryThrowing on every other code keeps a 500 or a 401 from being reported as "not in the inventory".
With a page size of 2, fetch every server and print how many each environment has, plus how many requests it took. A fresh API has 5 prod and 2 staging servers.
Show Solution
$page = 1
$servers = do {
$response = Invoke-RestMethod -Uri 'http://localhost:8765/api/servers' -Body @{ page = $page; per_page = 2 }
$response.items
$page++
} while ($page -le $response.total_pages)
"Fetched $($servers.Count) servers in $($page - 1) requests"
$servers | Group-Object -Property environment | Select-Object Name, CountFetched 7 servers in 4 requests
Name Count
---- -----
prod 5
staging 2Write Test-ApiHealth that takes a URL and returns $true only when the endpoint answers within
3 seconds with a JSON body whose status is ok. Every failure (timeout, refused connection, HTTP
error, wrong body) returns $false with a warning instead of throwing, so a monitoring script can
call it in a loop. Test it against /health, /api/slow?seconds=10, a port with nothing listening,
and /api/servers/web-01.
Show Solution
function Test-ApiHealth {
param(
[Parameter(Mandatory)] [string] $Uri,
[int] $TimeoutSec = 3
)
try {
$health = Invoke-RestMethod -Uri $Uri -TimeoutSec $TimeoutSec -ErrorAction Stop
return $health.status -eq 'ok'
}
catch {
Write-Warning "$Uri failed: $($_.Exception.Message)"
return $false
}
}
Test-ApiHealth -Uri 'http://localhost:8765/health'
Test-ApiHealth -Uri 'http://localhost:8765/api/slow?seconds=10'
Test-ApiHealth -Uri 'http://localhost:8769/health'
Test-ApiHealth -Uri 'http://localhost:8765/api/servers/web-01'True
WARNING: http://localhost:8765/api/slow?seconds=10 failed: The request was canceled due to the configured HttpClient.Timeout of 3 seconds elapsing.
False
WARNING: http://localhost:8769/health failed: Connection refused (localhost:8769)
False
FalseThe last case is the subtle one: /api/servers/web-01 answered 200, but its body has no status
of ok, so a check that only looked at the status code would have passed it.
Tested with: PowerShell 7.6.9 on Ubuntu 24.04 (WSL2) and Windows PowerShell 5.1.26100 on Windows 11,
November 2026. Every example ran against the practice API above (Python 3.12), restarted fresh for each
group of examples, and the outputs are pasted as printed; […] marks lines I trimmed. The 5.1 column
and the Zürich output come from Windows PowerShell 5.1 on the host calling the same API; nothing on
the Windows host was changed. The timings (130-second endpoint, 10 MB download) are single
measurements on one machine.
Written by The Dark Debugger
Engineer documenting the things that took me too long to learn, so they take you less time. Every PowerShell tutorial here is tested end to end before publishing.