PowerShell Lesson 7: Cloud and API Automation — REST, Az, AWS.Tools and Secrets

Every cloud is an HTTP API with a module on top. This lesson starts at the HTTP layer (Invoke-RestMethod against a local mock API that paginates, fails, rate-limits and checks tokens), adds secrets handling, then uses the same ideas through Az PowerShell and AWS.Tools: sign-in, context, read-only queries, idempotent changes and reports. OpsKit grows to v0.5 with an API client and a merged cloud inventory.
PowerShell 7.6 LTS (7.6.10)Az 16 · AWS.Tools 5 · SecretManagement 1.1Mock API: local only · FreeCloud parts optionalVerified · 2026-11-24
Position in the Learning Path Lessons 1–2 gave you the object pipeline and the language; Lesson 3 turned scripts into advanced functions (OpsKit v0.1: Get-OpsServer, Get-OpsConfig, Test-OpsEndpoint); Lesson 4 packaged them as a module (v0.2); Lesson 5 added error handling, -WhatIf, retries and logs (v0.3, Invoke-OpsBackup); Lesson 6 went parallel and remote (v0.4, Invoke-OpsHealthCheck). This lesson points the same tools at HTTP APIs and clouds. Milestone: OpsKit v0.5 adds Invoke-OpsApi (bearer token from SecretManagement or an environment variable, retries only for transient failures, Retry-After, pagination) and Get-OpsCloudInventory (one object model for the local inventory, the API, Azure and AWS). Lesson 8 tests and releases it as v1.0. For cloud fundamentals see the Azure and AWS courses.
Overall Learning Objectives
  • Choose between Invoke-RestMethod (body → objects) and Invoke-WebRequest (status, headers, raw content); send JSON correctly with ConvertTo-Json -Depth and -ContentType; read status codes with -StatusCodeVariable, -ResponseHeadersVariable and -SkipHttpErrorCheck.
  • Handle HTTP errors as what they are in 7.6: statement-terminating errors that -ErrorAction SilentlyContinue does not hide; read the API's error body from $_.ErrorDetails.Message.
  • Consume real APIs: follow pages with -FollowRelLink or a nextLink loop; know exactly what -MaximumRetryCount retries (all 4xx/5xx including 404 and POST, honoring Retry-After on 429 — but not timeouts or refused connections); separate -ConnectionTimeoutSeconds (alias -TimeoutSec) from -OperationTimeoutSeconds — this lesson's core animation.
  • Keep secrets out of code, history and logs: -Authentication Bearer -Token <SecureString>, environment variables injected by CI, SecretManagement + SecretStore, and token-less CI with managed identity / OIDC federated credentials.
  • Sign in to Azure with the right method for each context (interactive, device code, managed identity, service principal with certificate, federated token), pin the context with Set-AzContext, and run read-only queries.
  • Install only the AWS.Tools modules you need, resolve credentials and region predictably (profiles, SSO, environment variables, roles), and shape Get-EC2Instance's Reservations → Instances output; know V5's auto-iteration and -Select.
  • Make cloud changes idempotent: get → compare → set, tags as ownership, SupportsShouldProcess wrappers, specific handling of “not found”, and the verified trap that -WhatIf from a script does not reach module functions.
  • Shape nested cloud JSON into flat reports (-ExpandProperty, member enumeration, calculated properties), query Azure Resource Graph with KQL, export CSV/JSON — and ship OpsKit v0.5 plus an inventory sync with exit codes that survives injected failures.

1-Hour Time Allocation

#TimeModuleCore ContentAnimation / InteractiveLab (~/pslab)
0Before ClassMock API and accountsStart-MockApi.ps1: a local HttpListener API on 127.0.0.1:5050 (pagination, 503, 429, slow, bearer token); optional Azure / AWS sandbox; modulesSelf-check checklistStart, probe and stop the mock API
100–06IRM vs IWRJSON → PSCustomObject, -Headers, -Body + ConvertTo-Json -Depth, -ContentType, -StatusCodeVariable, -SkipHttpErrorCheck, ErrorDetailsRequest → response → objectGET, POST and a 404 three ways
206–13Real APIs-FollowRelLink, nextLink loops, -MaximumRetryCount / -RetryIntervalSec, 429 + Retry-After, connection vs operation timeoutscore animation: a paginated, retried API callMeasure what really gets retried
313–21Auth and secretsBearer tokens as SecureString, -AllowUnencryptedAuthentication, env vars in CI, PSReadLine history filter, SecretManagement / SecretStore, managed identity, OIDCWhere does the token come from?Token from an env var; check what history would save
421–28Az PowerShellModular install, Connect-AzAccount parameter sets, contexts, Set-AzContext, Get-AzResourceGroup, Get-AzVM -Status, -WhatIf, Az vs azSign-in method → context → queryInspect Az metadata offline; optional sandbox queries
528–35AWS.ToolsAWS.Tools.Installer, profiles and SSO, credential resolution, -Region / Set-DefaultAWSRegion, Get-EC2Instance, Get-S3Bucket, -Select, auto-iterationCredential and region resolutionModules saved to a folder; region defaults offline
635–42Idempotent changesGet → compare → set, tags, ShouldProcess wrappers, not-found vs real errors, preference propagation into modulesGet-then-set decision pathSet-LabServerTag run twice against the mock API
742–50Cloud dataNested JSON, -ExpandProperty, calculated properties, Search-AzGraph + KQL, CSV/JSON reports, cost-safe queriesFrom raw JSON to a reportFlatten EC2 and Resource Graph samples into CSV
850–60OpsKit v0.5Invoke-OpsApi (token, transient-only retries, backoff, pagination, ShouldProcess) and Get-OpsCloudInventory (Local / Api / Azure / Aws)Invoke-OpsApi flow + troubleshooting treeAdd both functions, bump to 0.5.0, run against the mock
—After ClassCheat sheet · Integrated labSync-OpsInventory.ps1: inventory sync against a mock API with drift and injected 503/429 faults; exit codes 0 / 1 / 2Final quiz (12 questions)Converges, then is idempotent

Knowledge Coverage Matrix

Target skillsM1M2M3M4M5M6M7M8Key commandsLab
Call REST APIs and read responses✓✓✓··✓·✓Invoke-RestMethod, Invoke-WebRequest, -StatusCodeVariableM1, M8
Handle HTTP errors and error bodies✓✓✓··✓·✓try/catch, $_.ErrorDetails.Message, -SkipHttpErrorCheckM1, M6
Pagination, retries, rate limits, timeouts·✓··✓·✓✓-FollowRelLink, -MaximumRetryCount, Retry-After, -ConnectionTimeoutSecondsM2, integrated lab
Keep secrets out of code and history··✓✓✓··✓-Token, Get-Secret, $env:, OIDCM3, M8
Sign in and pin the cloud context··✓✓✓✓··Connect-AzAccount, Set-AzContext, Set-AWSCredential, -RegionM4, M5
Idempotent, previewable changes···✓·✓·✓SupportsShouldProcess, -WhatIf, Update-AzTag -Operation MergeM6, integrated lab
Shape nested JSON into reports✓✓·✓✓·✓✓-ExpandProperty, @{n=;e=}, Search-AzGraph, Export-CsvM7
Package it in OpsKit with exit codes·····✓·✓Invoke-OpsApi, Get-OpsCloudInventory, exit 0/1/2M8, integrated lab

Excluded from this lesson (and where to learn it)

TopicWhy not in this lessonWhere to learn it
Azure and AWS services themselves (networking, IAM / RBAC design, pricing)This lesson automates them; it does not teach the platformsAzure course, AWS course
Bicep / ARM templates, CloudFormation, TerraformDeclarative infrastructure is a different tool category; PowerShell is used here for queries, glue and targeted changesTerraform course
Microsoft Graph PowerShell SDK (Entra ID users, groups, apps)Same patterns (Connect-, contexts, paging) but a large separate SDKMicrosoft Learn: Microsoft Graph PowerShell
OAuth flows in depth (authorization code, PKCE, token refresh)Az and AWS.Tools handle them; this lesson uses bearer tokens as givenIdentity provider documentation
Error handling fundamentals (terminating vs non-terminating, $ErrorActionPreference)Assumed from Lesson 5; applied here to HTTPLesson 5
Running many API calls in parallel (ForEach-Object -Parallel, thread jobs)Covered with throttling in Lesson 6; parallel calls also multiply 429sLesson 6
Pester mocks for Invoke-RestMethod, CI release of OpsKitTesting and releaseLesson 8

How to use these materials

10 pages per module
Principles · Diagram · Animation · Commands · Lab · Production case · Troubleshooting · Quiz · Voice · Video. Start the mock API (Module 0) before Module 1 and keep it running; every “Actual output” in Modules 1–3, 6 and 8 came from it. The paginated, retried call in Module 2 is the thread of the lesson.
Learning progress
A quiz score of 70% or more, or clicking “Mark this module complete”, counts toward progress. Progress is saved in this browser's local storage (if the browser blocks local storage, it resets on refresh).
Voice narration
The “Voice” page uses the browser's built-in Web Speech API (en-US) to read the narration script. Without a voice pack the script can still be read, or passed to a TTS tool.
Version notes Verified 2026-11-24 on PowerShell 7.6.10 (.NET 10.0.15) on Windows. Module versions used for metadata: Az 16.0.0 (Az.Accounts 5.5.0, Az.Resources 10.0.0, Az.Compute 11.6.0, Az.ResourceGraph 1.3.0), AWS.Tools 5.0.344 (AWS.Tools.Installer 2.0.6), Microsoft.PowerShell.SecretManagement 1.1.2 and SecretStore 1.0.6, PSReadLine 2.4.5, Azure CLI 2.84.0. Everything marked “Actual output” ran locally against the mock API or read module metadata; no cloud sign-in was performed, so every Azure / AWS result is marked “Expected output” and listed under Known limitations. The -ConnectionTimeoutSeconds / -OperationTimeoutSeconds parameters exist since PowerShell 7.4; on 7.6 -TimeoutSec is an alias of -ConnectionTimeoutSeconds.

Module 0 · Prep: a local mock API and optional cloud accounts

Every HTTP behavior in this lesson — pagination, transient 503s, 429 with Retry-After, slow responses, bearer tokens, JSON error bodies — comes from Start-MockApi.ps1, a 190-line PowerShell script that serves ~/pslab/data/inventory.json on 127.0.0.1. Cloud accounts are optional and only needed for the Azure / AWS “Expected output” sections.
Before class ≈ 15 minMock API: localhost only · FreeCloud: sandbox only, read-only
Prerequisites
  • Lessons 1–6, in particular: error records and try/catch (Lesson 5), SupportsShouldProcess (Lessons 3 and 5), thread jobs (Lesson 6), the OpsKit module in ~/pslab/OpsKit (v0.4).
  • PowerShell 7.4 or later (7.6 recommended). Start-ThreadJob comes from the bundled Microsoft.PowerShell.ThreadJob module.
  • Optional: an Azure sandbox subscription where you hold Reader (and Contributor on one empty resource group for Module 6), and/or an AWS sandbox account with a read-only role. Never use a production subscription or account for a course.

Warm-up: answer from memory (30 seconds)

1. In Lesson 5, what is the difference between a non-terminating and a statement-terminating error, and which one does try/catch catch without -ErrorAction Stop?

A non-terminating error (Write-Error, most “item not found” cmdlet errors) is written to the error stream and the command continues; try/catch only sees it with -ErrorAction Stop. A statement-terminating error (a .NET exception, $PSCmdlet.ThrowTerminatingError()) stops the statement and is always caught. Module 1 shows that HTTP error responses from Invoke-RestMethod are of the second kind.

2. What does $using: do in a thread job or ForEach-Object -Parallel (Lesson 6)?

It copies a value from the caller's scope into the other runspace. Today the mock API runs in a thread job, so it shares your process but not your variables.

3. What does SupportsShouldProcess give a function, and where does the decision happen?

-WhatIf and -Confirm; the decision happens in $PSCmdlet.ShouldProcess(target, action). Module 6 adds an important rule about calling module functions from scripts.

Step 1: save Start-MockApi.ps1

Save the script below as ~/pslab/Start-MockApi.ps1. It uses only System.Net.HttpListener (part of .NET, works on Windows, Linux and macOS), listens only on 127.0.0.1, keeps all state in memory, and handles one request at a time — so a /slow call delays the next one, a useful reminder that real servers queue too. On Windows a non-administrator may listen on http://127.0.0.1:<port>/ without a URL ACL (verified on the lab machine); if your policy differs, change -Port.

<#
.SYNOPSIS
    A small local REST API for the PowerShell course, Lesson 7.
.DESCRIPTION
    Serves ~/pslab/data/inventory.json over HTTP on 127.0.0.1 only, with the
    behaviors real cloud APIs have: pagination, transient 503s, 429 + Retry-After,
    slow responses, bearer-token checks and JSON error bodies. No dependencies,
    single-threaded (one request at a time), state is kept in memory only.

    Public (no token):
    GET  /health                             {"status":"ok"}
    GET  /api/servers?env=&page=&pageSize=   one page + nextLink + Link: rel="next"
    GET  /api/servers/{env}/{name}           one server; 404 with a JSON error body
    POST /api/servers                        echo with 201; 400 if Name is missing
    GET|PUT /api/servers/{env}/{name}/tags   tags kept in memory (idempotency lab)
    GET  /flaky?key=k&fail=2                 503 'fail' times per key, then 200
    GET  /ratelimit?key=k&after=2            429 + Retry-After once per key, then 200
    GET  /slow?sec=5                         waits, then 200
    GET  /stats                              request counters
    POST /shutdown                           stops the server
    Needs "Authorization: Bearer <token>":
    GET  /api/secure/servers?page=&pageSize= paginated, like /api/servers
    POST /api/secure/servers                 create (stored in memory); 409 if it exists
    PUT  /api/secure/servers/{env}/{name}    update IP / Region / Monitored
.EXAMPLE
    $api = Start-ThreadJob -FilePath ~/pslab/Start-MockApi.ps1
    Invoke-RestMethod http://127.0.0.1:5050/health
.EXAMPLE
    # Fault injection for the integrated lab: every 3rd secure request fails
    # (503 and 429 alternately), and the data has drifted from inventory.json.
    $api = Start-ThreadJob { & ~/pslab/Start-MockApi.ps1 -FailEvery 3 -Drift }
#>
#Requires -Version 7.4
param(
    [int]$Port = 5050,
    [string]$DataPath = (Join-Path $HOME 'pslab' 'data' 'inventory.json'),
    [string]$Token = 'lab-token-7f3a',
    [int]$FailEvery = 0,
    [switch]$Drift
)
$ErrorActionPreference = 'Stop'
$servers = [System.Collections.Generic.List[object]]::new()
(Get-Content -LiteralPath $DataPath -Raw | ConvertFrom-Json) | ForEach-Object { $servers.Add($_) }
if ($Drift) {   # the "cloud" no longer matches the inventory file
    $servers.RemoveAll({ param($s) $s.Env -eq 'prod' -and $s.Name -eq 'bastion-01' }) | Out-Null
    ($servers | Where-Object { $_.Env -eq 'dev' -and $_.Name -eq 'db-01' }).IP = '10.10.1.99'
}
$base    = "http://127.0.0.1:$Port"
$tags    = @{}        # "env/name" -> hashtable of tags
$counter = @{}        # "flaky:key" / "rate:key" -> int
$stats   = [ordered]@{ requests = 0; e401 = 0; e429 = 0; e503 = 0; secure = 0 }

$listener = [System.Net.HttpListener]::new()
$listener.Prefixes.Add("$base/")
$listener.Start()
Write-Output "Mock API listening on $base/ (FailEvery=$FailEvery, Drift=$Drift)"

function Send-Json($Context, [int]$Status, $Body, [hashtable]$Headers = @{}) {
    $res = $Context.Response
    $res.StatusCode = $Status
    $res.ContentType = 'application/json; charset=utf-8'
    foreach ($h in $Headers.Keys) { $res.AddHeader($h, $Headers[$h]) }
    $res.AddHeader('X-Request-Id', [guid]::NewGuid().ToString('N').Substring(0, 12))
    if ($null -ne $Body) {
        $bytes = [Text.Encoding]::UTF8.GetBytes(($Body | ConvertTo-Json -Depth 6 -Compress))
        $res.ContentLength64 = $bytes.Length
        $res.OutputStream.Write($bytes, 0, $bytes.Length)
    }
    $res.Close()
}
function New-ApiError([string]$Code, [string]$Message) { [ordered]@{ error = [ordered]@{ code = $Code; message = $Message } } }
function Read-Body($Request) { [IO.StreamReader]::new($Request.InputStream).ReadToEnd() | ConvertFrom-Json }
function Send-Page($Context, $Query, [string]$Route) {
    $list = @($servers | Where-Object { -not $Query['env'] -or $_.Env -eq $Query['env'] })
    $size = [int]($Query['pageSize'] ?? 5); $page = [int]($Query['page'] ?? 1)
    $items = @($list | Select-Object -Skip (($page - 1) * $size) -First $size)
    $next = $null; $h = @{}
    if ($page * $size -lt $list.Count) {
        $next = "$base$Route`?page=$($page + 1)&pageSize=$size" + $(if ($Query['env']) { "&env=$($Query['env'])" })
        $h['Link'] = "<$next>; rel=`"next`""
    }
    Send-Json $Context 200 ([ordered]@{ value = $items; count = $list.Count; page = $page; nextLink = $next }) $h
}

$running = $true
while ($running -and $listener.IsListening) {
    $task = $listener.GetContextAsync()
    while (-not $task.Wait(250)) { }          # short waits keep Stop-Job responsive
    $ctx = $task.Result
    $req = $ctx.Request
    $stats.requests++
    $path = $req.Url.AbsolutePath.TrimEnd('/')
    $q = [System.Web.HttpUtility]::ParseQueryString($req.Url.Query)
    try {
        switch -Regex ($path) {
            '^/health$' { Send-Json $ctx 200 ([ordered]@{ status = 'ok'; version = 'mock-1.0' }); break }

            '^/api/servers$' {
                if ($req.HttpMethod -eq 'POST') {
                    $body = Read-Body $req
                    if (-not $body.Name) { Send-Json $ctx 400 (New-ApiError 'InvalidRequest' "Property 'Name' is required."); break }
                    Send-Json $ctx 201 $body @{ Location = "$base/api/servers/$($body.Env)/$($body.Name)" }; break
                }
                Send-Page $ctx $q '/api/servers'; break
            }

            '^/api/servers/([^/]+)/([^/]+)/tags$' {
                $key = "$($Matches[1])/$($Matches[2])"
                if (-not ($servers | Where-Object { "$($_.Env)/$($_.Name)" -eq $key })) {
                    Send-Json $ctx 404 (New-ApiError 'NotFound' "Server '$key' was not found."); break
                }
                if ($req.HttpMethod -eq 'PUT') { $tags[$key] = [IO.StreamReader]::new($req.InputStream).ReadToEnd() | ConvertFrom-Json -AsHashtable }
                Send-Json $ctx 200 ([ordered]@{ server = $key; tags = ($tags[$key] ?? @{}) }); break
            }

            '^/api/servers/([^/]+)/([^/]+)$' {
                $s = $servers | Where-Object { $_.Env -eq $Matches[1] -and $_.Name -eq $Matches[2] }
                if ($s) { Send-Json $ctx 200 $s }
                else { Send-Json $ctx 404 (New-ApiError 'NotFound' "Server '$($Matches[1])/$($Matches[2])' was not found.") }
                break
            }

            '^/api/secure/' {
                if ($req.Headers['Authorization'] -ne "Bearer $Token") {
                    $stats.e401++
                    Send-Json $ctx 401 (New-ApiError 'Unauthorized' 'Missing or invalid bearer token.') @{ 'WWW-Authenticate' = 'Bearer realm="pslab"' }; break
                }
                $stats.secure++
                if ($FailEvery -gt 0 -and $stats.secure % $FailEvery -eq 0) {     # injected faults
                    if (($stats.secure / $FailEvery) % 2) { $stats.e503++; Send-Json $ctx 503 (New-ApiError 'ServiceUnavailable' 'Injected fault.') }
                    else { $stats.e429++; Send-Json $ctx 429 (New-ApiError 'TooManyRequests' 'Injected rate limit.') @{ 'Retry-After' = '1' } }
                    break
                }
                if ($path -eq '/api/secure/servers' -and $req.HttpMethod -eq 'GET') { Send-Page $ctx $q '/api/secure/servers'; break }
                if ($path -eq '/api/secure/servers' -and $req.HttpMethod -eq 'POST') {
                    $b = Read-Body $req
                    if (-not $b.Name -or -not $b.Env) { Send-Json $ctx 400 (New-ApiError 'InvalidRequest' 'Name and Env are required.'); break }
                    if ($servers | Where-Object { $_.Env -eq $b.Env -and $_.Name -eq $b.Name }) {
                        Send-Json $ctx 409 (New-ApiError 'Conflict' "Server '$($b.Env)/$($b.Name)' already exists."); break
                    }
                    $servers.Add($b); Send-Json $ctx 201 $b; break
                }
                if ($path -match '^/api/secure/servers/([^/]+)/([^/]+)$' -and $req.HttpMethod -eq 'PUT') {
                    $s = $servers | Where-Object { $_.Env -eq $Matches[1] -and $_.Name -eq $Matches[2] }
                    if (-not $s) { Send-Json $ctx 404 (New-ApiError 'NotFound' "Server '$($Matches[1])/$($Matches[2])' was not found."); break }
                    $b = Read-Body $req
                    foreach ($p in 'IP', 'Region', 'Monitored') { if ($null -ne $b.$p) { $s.$p = $b.$p } }
                    Send-Json $ctx 200 $s; break
                }
                Send-Json $ctx 405 (New-ApiError 'MethodNotAllowed' "$($req.HttpMethod) $path is not supported."); break
            }

            '^/flaky$' {
                $k = 'flaky:' + ($q['key'] ?? 'default'); $fail = [int]($q['fail'] ?? 2)
                $counter[$k] = 1 + ($counter[$k] ?? 0)
                if ($counter[$k] -le $fail) {
                    $stats.e503++
                    Send-Json $ctx 503 (New-ApiError 'ServiceUnavailable' "Try again (attempt $($counter[$k]))."); break
                }
                Send-Json $ctx 200 ([ordered]@{ status = 'ok'; attempt = $counter[$k] }); break
            }

            '^/ratelimit$' {
                $k = 'rate:' + ($q['key'] ?? 'default')
                $counter[$k] = 1 + ($counter[$k] ?? 0)
                if ($counter[$k] -eq 1) {
                    $stats.e429++
                    Send-Json $ctx 429 (New-ApiError 'TooManyRequests' 'Rate limit exceeded.') @{ 'Retry-After' = ($q['after'] ?? '2') }; break
                }
                Send-Json $ctx 200 ([ordered]@{ status = 'ok'; attempt = $counter[$k] }); break
            }

            '^/slow$' {
                Start-Sleep -Seconds ([int]($q['sec'] ?? 5))
                Send-Json $ctx 200 ([ordered]@{ status = 'ok'; slow = $true }); break
            }

            '^/stats$'    { Send-Json $ctx 200 $stats; break }
            '^/shutdown$' { Send-Json $ctx 200 ([ordered]@{ status = 'stopping' }); $running = $false; break }
            default       { Send-Json $ctx 404 (New-ApiError 'NotFound' "No route for $path.") }
        }
    }
    catch {
        try { Send-Json $ctx 500 (New-ApiError 'InternalError' $_.Exception.Message) } catch { }
    }
}
$listener.Stop()
$listener.Close()
Write-Output 'Mock API stopped.'
EndpointBehaviorUsed in
GET /api/servers?env=&page=&pageSize=One page (default 5 items) + nextLink in the body + Link: <…>; rel="next" headerM1, M2
GET /api/servers/{env}/{name}One server; 404 with {"error":{"code":"NotFound",…}}M1, M2, M8
POST /api/serversEcho with 201 and a Location header; 400 without Name; 500 when the body is not JSONM1
GET|PUT /api/servers/{env}/{name}/tagsTags kept in memoryM6
/flaky?key=&fail=2 · /ratelimit?key=&after=2 · /slow?sec=5503 fail times per key, then 200 · 429 + Retry-After once per key · a delayed 200M2, M8
/api/secure/servers (GET, POST) · /api/secure/servers/{env}/{name} (PUT)Needs Authorization: Bearer lab-token-7f3a; 401 + WWW-Authenticate otherwise. -FailEvery N injects 503/429 on every Nth call; -Drift removes prod/bastion-01 and changes the IP of dev/db-01M3, M8, integrated lab

Step 2: start it, probe it, stop it

Set-Location ~/pslab
$api = Start-ThreadJob -FilePath ./Start-MockApi.ps1
Start-Sleep -Seconds 1
$api | Receive-Job
Invoke-RestMethod http://127.0.0.1:5050/health
Mock API listening on http://127.0.0.1:5050/ (FailEvery=0, Drift=False)

status version
------ -------
ok     mock-1.0

The thread job runs inside your pwsh process: closing the terminal stops the API. Keep $api for the rest of the lesson. A second copy on the same port fails immediately:

$api2 = Start-ThreadJob -FilePath ./Start-MockApi.ps1; Start-Sleep 1
$api2 | Receive-Job; $api2.State; $api2 | Remove-Job
Exception calling "Start" with "0" argument(s): "Failed to listen on prefix 'http://127.0.0.1:5050/' because it conflicts with an existing registration on the machine."
Failed

Stop it cleanly when you are done (and restart it with the first block whenever a module says so):

Invoke-RestMethod http://127.0.0.1:5050/shutdown -Method Post
$api | Wait-Job -Timeout 5 | Receive-Job
$api | Remove-Job
Invoke-RestMethod http://127.0.0.1:5050/health -TimeoutSec 2
status
------
stopping

Mock API stopped.
Invoke-RestMethod: No connection could be made because the target machine actively refused it. (127.0.0.1:5050)

Step 3: modules for this lesson

NeedInstall (your own machine)Notes
Nothing extra for Modules 1–3, 6–8 with the mock API—Invoke-RestMethod, ConvertFrom-Json, thread jobs and PSReadLine ship with PowerShell 7.6
SecretManagement + SecretStore (M3, M8)Install-PSResource Microsoft.PowerShell.SecretManagement, Microsoft.PowerShell.SecretStore -Scope CurrentUserOptional; OpsKit falls back to $env:OPSKIT_API_TOKEN
Az (M4, M6, M7)Install-PSResource Az.Accounts, Az.Resources, Az.Compute, Az.ResourceGraph -Scope CurrentUserInstall only the service modules you need; the Az 16.0.0 roll-up lists 102 modules in its manifest
AWS.Tools (M5)Install-PSResource AWS.Tools.Installer -Scope CurrentUser then Install-AWSToolsModule EC2, S3, SecurityToken -CleanupThe installer keeps all AWS.Tools modules on the same version

Just looking? To read commands and help without installing into your profile, save a module to a folder and add it to $env:PSModulePath in one session only — this is how the metadata in this lesson was produced:

$mods = Join-Path ~/pslab 'tmp' 'modules'
$null = New-Item -ItemType Directory -Force -Path $mods
Save-PSResource -Name Microsoft.PowerShell.SecretManagement, AWS.Tools.EC2 -Path $mods -TrustRepository
$env:PSModulePath = $mods + [IO.Path]::PathSeparator + $env:PSModulePath   # this session only
Get-Module -ListAvailable AWS.Tools.* | Format-Table Name, Version
Name             Version
----             -------
AWS.Tools.Common 5.0.344
AWS.Tools.EC2    5.0.344

Step 4 (optional): cloud sandboxes

  • Azure: a subscription you are allowed to experiment in; create one empty resource group rg-pslab-h7 with tag owner=<you>. Reader on the subscription is enough for Modules 4 and 7; Contributor on that one group for Module 6. Every command in this lesson is either read-only or shown with -WhatIf first.
  • AWS: an account with an SSO permission set or role that allows ec2:DescribeInstances and s3:ListAllMyBuckets. Configure it with the AWS CLI (aws configure sso); Module 5 reads that profile.
  • Cost: all queries in this lesson are free (Resource Graph, Describe*, List*). Nothing here creates billable resources.

Environment self-check checklist

Risks and cleanup The mock API binds to 127.0.0.1 only and is stopped by POST /shutdown, Stop-Job or closing pwsh. Its token lab-token-7f3a is a lab value — never reuse the pattern of a hard-coded token for anything real (Module 3). In the cloud: use a sandbox, read before you write, run every change with -WhatIf first, and tag what you create. Lab files go to ~/pslab/tmp; delete it at any time.

Module 1 · Invoke-RestMethod vs Invoke-WebRequest: JSON to objects, headers and status codes

00:00 – 06:00 · Both cmdlets send the same HTTP request through the same .NET HttpClient; they differ in what they give back. Invoke-RestMethod parses the body into objects; Invoke-WebRequest returns the whole response. And in 7.6 an HTTP error status is a statement-terminating error.
6 minMock API · real outputs★★★★★
Learning objectives
  • Predict the output type of Invoke-RestMethod (PSCustomObject from JSON, XmlDocument from XML, string otherwise) and of Invoke-WebRequest (BasicHtmlWebResponseObject with StatusCode, Headers, Content).
  • Send JSON bodies correctly: ConvertTo-Json -Depth + -ContentType 'application/json'; know what happens when you pass a hashtable to -Body.
  • Capture the status code and headers of a successful call with -StatusCodeVariable and -ResponseHeadersVariable.
  • Handle 4xx/5xx: try/catch on HttpResponseException, the API's error body in $_.ErrorDetails.Message, or -SkipHttpErrorCheck to get the body as a normal result.
Prerequisites: Module 0 (mock API running), Lesson 5 (error records). Importance:★★★★★ (every cloud SDK sits on top of exactly this)

What: two cmdlets, one HTTP stack

Invoke-RestMethod (alias irm)Invoke-WebRequest (alias iwr)
ReturnsThe body, converted: JSON → PSCustomObject (arrays are enumerated), XML/RSS → XmlDocument/items, anything else → stringA BasicHtmlWebResponseObject: StatusCode, StatusDescription, Headers (values are String[]), Content (string), RawContentLength, Links, Images
Status code and headersOnly via -StatusCodeVariable and -ResponseHeadersVariableAlways on the result object
Pagination helper-FollowRelLink / -MaximumFollowRelLink (Module 2)—
Typical useJSON APIs: you want the dataDownloads (-OutFile), health checks, debugging headers, non-JSON content

Both share every request parameter: -Method, -Headers, -Body, -ContentType, -Authentication/-Token, -MaximumRetryCount, timeouts, proxies, certificates, -SkipHttpErrorCheck. In PowerShell 7 neither uses Internet Explorer; -UseBasicParsing is accepted and ignored.

Why: types survive JSON, not CSV

Lesson 2 showed that Import-Csv turns everything into strings. JSON keeps types: the mock API's Monitored arrives as Boolean and Port as Int64 (verified below), so Where-Object Monitored just works. The price: nested objects need -Depth on the way out (ConvertTo-Json defaults to depth 2 and truncates with a warning).

How: request body rules

-Body valueWhat is sentVerified result against the mock API
($obj | ConvertTo-Json -Depth 10) + -ContentType 'application/json'JSON text201 Created ✓
A hashtable with -Method Postapplication/x-www-form-urlencoded form data (Name=x&Env=dev)500 — the API could not parse JSON ✗
A hashtable with -Method GetQuery string parametersUseful for ?env=prod&pageSize=5
A string without -ContentTypeSent with application/x-www-form-urlencoded for POSTMany APIs reject it with 415

When: errors — and why -ErrorAction does not help

For a 4xx/5xx response, PowerShell 7 raises a Microsoft.PowerShell.Commands.HttpResponseException as a statement-terminating error. Verified on 7.6.10: -ErrorAction SilentlyContinue and -ErrorAction Ignore still print the error and set $? to False. Your three options:

  1. try { … } catch { … } — read $_.Exception.Response.StatusCode (an HttpResponseMessage) and the API's error body in $_.ErrorDetails.Message (PowerShell pretty-prints JSON bodies there).
  2. -SkipHttpErrorCheck -StatusCodeVariable code — no error at all; the error body is returned as normal output and $code tells you what happened. Best for wrappers (OpsKit uses it in Module 8).
  3. Invoke-WebRequest -SkipHttpErrorCheck and branch on .StatusCode.
Common misconceptions① “-Body @{…} sends JSON” — it sends form data; convert with ConvertTo-Json. ② “ConvertTo-Json serializes everything” — default depth is 2; deeper levels become strings like System.Collections.Hashtable, with only a warning. ③ “-ErrorAction SilentlyContinue suppresses a 404” — not for HTTP errors; use try/catch or -SkipHttpErrorCheck. ④ “-StatusCodeVariable is set when the call fails” — verified: it stays empty when the error is thrown; it is useful with -SkipHttpErrorCheck. ⑤ “Headers are strings” — on 7.x every header value is a String[].

Request and response: what each cmdlet hands back

Request-Method POST -Uri …/api/servers-Headers @{ Authorization = … }-Body (ConvertTo-Json -Depth 10)-ContentType application/json HttpClient (.NET 10)timeouts · retries · proxy · TLSstatus line: 201 Createdheaders: Location, Content-Type …body: {"Name":"web-03",…} Invoke-RestMethodbody → PSCustomObjectstatus → -StatusCodeVariableheaders → -ResponseHeadersVariable Invoke-WebRequest.StatusCode .Headers (String[]).Content (string) → ConvertFrom-Json.RawContentLength .Links Status ≥ 400 (without -SkipHttpErrorCheck) HttpResponseException → statement-terminating error $_.Exception.Response.StatusCode · $_.ErrorDetails.Message (API error JSON) -ErrorAction SilentlyContinue does not hide it -SkipHttpErrorCheckerror body returned as outputbranch on -StatusCodeVariable
Figure 7-1: one request pipeline, two ways to receive the result, and two ways to deal with 4xx/5xx

ConvertTo-Json depth: what gets lost

$new (depth 0) Tags (1) cost (2) split (3) → "System.Collections.Hashtable" Default -Depth 2: levels 0–2 are serialized, deeper objects are converted with ToString() You get “WARNING: Resulting JSON is truncated …” on the warning stream — easy to miss in a pipeline or CI log Always pass -Depth (OpsKit uses 10) for request bodies
Figure 7-2: the depth limit is counted from the object you pipe in; the API receives a string where it expected an object

Request → response → object

Choose a call, then step through what PowerShell sends, what the mock API answers, and what ends up in your variable.

Ready.
Real mechanism behind the animation Both cmdlets derive from WebRequestPSCmdlet. It builds an HttpRequestMessage, sends it through an HttpClient, and checks IsSuccessStatusCode. On failure (and no -SkipHttpErrorCheck) it reads the body into ErrorDetails and calls ThrowTerminatingError — which is why -ErrorAction cannot silence it. On success, Invoke-RestMethod looks at Content-Type and converts JSON with the same code as ConvertFrom-Json.

Command table

Command / parameterPurposeNotes
Invoke-RestMethod $uriGET and convert the bodyJSON arrays are enumerated into the pipeline
Invoke-WebRequest $uriWhole response.StatusCode, .Headers['Content-Type'], .Content
-Method Post|Put|Patch|DeleteHTTP verb-CustomMethod for anything else
-Headers @{ 'X-Api-Version' = '2026-01' }Request headersUse -Authentication/-Token for auth (Module 3)
-Body ($o | ConvertTo-Json -Depth 10) -ContentType 'application/json'JSON bodyNever rely on the default depth of 2
-StatusCodeVariable sc -ResponseHeadersVariable hStatus and headers from irmVariable names without $
-SkipHttpErrorCheckTreat 4xx/5xx as normal outputCombine with -StatusCodeVariable
$_.ErrorDetails.MessageAPI error body inside catch| ConvertFrom-Json to read error.code
$_.Exception.ResponseHttpResponseMessage in catch.StatusCode, .Headers.RetryAfter, .ReasonPhrase
-OutFile path [-Resume]Download to a fileAdd -PassThru to also get the result

GET: JSON becomes typed objects

$base = 'http://127.0.0.1:5050'
$s = Invoke-RestMethod "$base/api/servers/prod/edge-01"
$s
$s.GetType().FullName
'{0} / {1}' -f $s.Monitored.GetType().Name, $s.Port.GetType().Name
Name      : edge-01
Env       : prod
Region    : ca-central-1
IP        : 10.30.2.51
Role      : web,api
Monitored : True
Port      : 8080

System.Management.Automation.PSCustomObject
Boolean / Int64

The same call with Invoke-WebRequest

$r = Invoke-WebRequest "$base/api/servers/prod/edge-01"
$r.StatusCode
$r.Headers['Content-Type']
$r.Headers.Keys -join ', '
$r.Content
($r.Content | ConvertFrom-Json).Role
$r.GetType().Name; $r.Headers['Content-Type'].GetType().Name; $r.RawContentLength
200
application/json; charset=utf-8
Server, X-Request-ID, Date, Content-Length, Content-Type
{"Name":"edge-01","Env":"prod","Region":"ca-central-1","IP":"10.30.2.51","Role":"web,api","Monitored":true,"Port":8080}
web,api
BasicHtmlWebResponseObject
String[]
119

A paged list: the envelope and the items

$page = Invoke-RestMethod "$base/api/servers?pageSize=3&env=prod"
$page | Format-List count, page, nextLink
$page.value | Format-Table Name, Env, IP, Monitored
count    : 6
page     : 1
nextLink : http://127.0.0.1:5050/api/servers?page=2&pageSize=3&env=prod

Name   Env  IP         Monitored
----   ---  --         ---------
web-01 prod 10.30.1.41      True
web-02 prod 10.30.1.42      True
api-01 prod 10.30.1.43      True

Most cloud APIs wrap lists in an envelope: Azure uses value + nextLink, Microsoft Graph value + @odata.nextLink, AWS NextToken. Always ask “where are the items, and where is the next page?” (Module 2).

POST: depth, content type, status and headers

$new = @{
    Name = 'web-03'; Env = 'prod'; Region = 'canadacentral'
    Tags = @{ owner = 'team-a'; cost = @{ center = 'cc-100'; split = @{ a = 60; b = 40 } } }
}
$new | ConvertTo-Json -Compress          # default -Depth 2
WARNING: Resulting JSON is truncated as serialization has exceeded the set depth of 2.
{"Tags":{"owner":"team-a","cost":{"center":"cc-100","split":"System.Collections.Hashtable"}},"Name":"web-03","Env":"prod","Region":"canadacentral"}
$created = Invoke-RestMethod "$base/api/servers" -Method Post `
    -Body ($new | ConvertTo-Json -Depth 10) -ContentType 'application/json' `
    -StatusCodeVariable status -ResponseHeadersVariable headers
"status=$status"
$headers['Location']
$created.Tags.cost.split.a
status=201
http://127.0.0.1:5050/api/servers/prod/web-03
60

The hashtable-body trap

try {
    Invoke-RestMethod "$base/api/servers" -Method Post -Body @{ Name = 'x'; Env = 'dev' }
} catch {
    [int]$_.Exception.Response.StatusCode
    ($_.ErrorDetails.Message | ConvertFrom-Json).error.message
}
500
Conversion from JSON failed with error: Unexpected character encountered while parsing value: E. Path '', line 0, position 0.

The server received Env=dev&Name=x (form encoding) and its JSON parser failed. Real APIs answer 400 or 415; the lesson is the same.

A 404, three ways

try {
    Invoke-RestMethod "$base/api/servers/prod/web-99"
} catch {
    $_.Exception.GetType().FullName
    $_.Exception.Message
    [int]$_.Exception.Response.StatusCode
    $_.ErrorDetails.Message
    "code=" + ($_.ErrorDetails.Message | ConvertFrom-Json).error.code
}
Microsoft.PowerShell.Commands.HttpResponseException
Response status code does not indicate success: 404 (Not Found).
404

{
  "error": {
    "code": "NotFound",
    "message": "Server 'prod/web-99' was not found."
  }
}
code=NotFound
$body = Invoke-RestMethod "$base/api/servers/prod/web-99" -SkipHttpErrorCheck -StatusCodeVariable code
"code=$code"
$body.error

$res = Invoke-WebRequest "$base/api/servers/prod/web-99" -SkipHttpErrorCheck
'{0} {1}' -f $res.StatusCode, $res.StatusDescription
code=404

code    : NotFound
message : Server 'prod/web-99' was not found.

404 NotFound
Invoke-RestMethod "$base/api/servers/prod/web-99" -ErrorAction SilentlyContinue
"after: `$? = $?"
Invoke-RestMethod:
{
  "error": {
    "code": "NotFound",
    "message": "Server 'prod/web-99' was not found."
  }
}
after: $? = False

How to verify: $Error[0].Exception.GetType().Name after a failed call is HttpResponseException; -ErrorAction Ignore behaves the same (also verified). Common mistake: wrapping a call in -ErrorAction SilentlyContinue and testing if (-not $result) — the error still reaches logs and CI marks the step red, while your script believes “not found”. Production use: in libraries use -SkipHttpErrorCheck + -StatusCodeVariable and turn each status class into a deliberate decision (Module 8); in scripts use try/catch and log ErrorDetails.Message, which usually contains the provider's error code and a request ID.

Goal: Read, create and fail against the mock API and explain every result. Environment: pwsh 7.4+, mock API from Module 0. Cost: none; nothing leaves 127.0.0.1.

Start the API if it is not running:
if (-not (Get-Job | Where-Object { $_.State -eq 'Running' -and $_.Command -like '*MockApi*' })) {
    $api = Start-ThreadJob -FilePath ~/pslab/Start-MockApi.ps1; Start-Sleep 1
}
$base = 'http://127.0.0.1:5050'
(Invoke-RestMethod "$base/health").status
ok
Count prod servers that are monitored, using typed JSON (no string comparison needed):
$prod = (Invoke-RestMethod "$base/api/servers?env=prod&pageSize=50").value
@($prod | Where-Object Monitored).Count
4

With servers.csv you needed -eq 'true' (Lesson 1, Module 6); JSON gives real booleans.

Compare IRM and IWR for the same URL: print the status code, the Content-Length header and the parsed IP with IWR only.
$r = Invoke-WebRequest "$base/api/servers/dev/db-01"
'{0} {1} {2}' -f $r.StatusCode, $r.Headers['Content-Length'][0], ($r.Content | ConvertFrom-Json).IP
200 113 10.10.1.23
Write a function that returns $null for 404 and throws for everything else:
function Get-LabServer([string]$Env, [string]$Name) {
    $r = Invoke-RestMethod "$base/api/servers/$Env/$Name" -SkipHttpErrorCheck -StatusCodeVariable sc
    switch ($sc) {
        200     { $r }
        404     { $null }
        default { throw "GET $Env/$Name failed: HTTP $sc $($r.error.message)" }
    }
}
Get-LabServer prod web-01 | Select-Object Name, IP
$null -eq (Get-LabServer prod web-99)
Name   IP
----   --
web-01 10.30.1.41
True
Break it on purpose: send a nested body without -Depth and look at what arrives (the mock echoes the body).
$o = @{ Name = 'x'; Env = 'dev'; Tags = @{ a = @{ b = @{ c = 1 } } } }
(Invoke-RestMethod "$base/api/servers" -Method Post -Body ($o | ConvertTo-Json) -ContentType 'application/json').Tags.a.b
WARNING: Resulting JSON is truncated as serialization has exceeded the set depth of 2.
System.Collections.Hashtable
Cleanup: nothing to delete; keep the API running for Module 2.

Case 1: tags silently became “System.Collections.Hashtable”

Problem: A pipeline that created resources through a REST API wrote cost-center tags. Weeks later finance found thousands of resources tagged "split": "System.Collections.Hashtable". Root cause: the body was built with ConvertTo-Json without -Depth; the truncation warning went to the warning stream that the CI system did not show. Fix: always pass -Depth (and in 7.x consider $PSDefaultParameterValues['ConvertTo-Json:Depth'] = 10 in scripts); add a test that round-trips the body (ConvertTo-Json | ConvertFrom-Json) and compares a deep value.

Case 2: “not found” logic that also swallowed 401s

Problem: A cleanup script checked $x = Invoke-RestMethod $uri -ErrorAction SilentlyContinue; if (-not $x) { create }. After a token expired, every check “found nothing” and the script tried to recreate 200 resources (all failed, with 200 error e-mails). Root cause: treating every failure as “missing”. Fix: branch on the status code: 404 → missing, 401/403 → stop the run, 429/5xx → retry (Module 2). -SkipHttpErrorCheck -StatusCodeVariable makes this explicit.

Case 3: a header value that “never matched”

Problem: if ($r.Headers['Content-Type'] -eq 'application/json') was always false. Root cause: on PowerShell 7 header values are String[], and the value is application/json; charset=utf-8; -eq on an array filters instead of comparing. Fix: $r.Headers['Content-Type'][0] -like 'application/json*'.

Common errors and fixes

Response status code does not indicate success: 400 (Bad Request) / 415 (Unsupported Media Type)

Cause: body not JSON (hashtable or string without -ContentType), or a property missing because of depth truncation.

$json = $body | ConvertTo-Json -Depth 10
$json            # look at it before sending
Invoke-RestMethod $uri -Method Post -Body $json -ContentType 'application/json'

Fix: print $_.ErrorDetails.Message; APIs usually name the bad field.

The error still shows although I used -ErrorAction SilentlyContinue

Cause: HTTP errors are statement-terminating in PowerShell 7.

try { Invoke-RestMethod $uri } catch { if ($_.Exception.Response.StatusCode -eq 'NotFound') { $null } else { throw } }
Output is a string instead of objects

Cause: the server did not send Content-Type: application/json, so Invoke-RestMethod returned text.

(Invoke-WebRequest $uri).Headers['Content-Type']
Invoke-RestMethod $uri | ConvertFrom-Json
Invoke-WebRequest prints a progress bar and is slow in scripts

Cause: progress rendering for large downloads (much faster in 7.x than in 5.1, but still noise in CI).

$ProgressPreference = 'SilentlyContinue'
The term 'irm' works here but my script fails on another machine

Cause: aliases in scripts; curl and wget are no longer aliases in PowerShell 7 (they run the native tools).

Fix: full names in scripts: Invoke-RestMethod, Invoke-WebRequest.

Command-line exercises
1. Get the status code and the X-Request-Id header of a GET, using Invoke-RestMethod only.
$null = Invoke-RestMethod "$base/health" -StatusCodeVariable sc -ResponseHeadersVariable h
"$sc $($h['X-Request-Id'][0])"
2. Send @{ Name='web-04'; Env='dev'; Meta=@{ a=@{ b=@{ c=1 } } } } as JSON so that c survives, and prove it from the echo.
$o = @{ Name='web-04'; Env='dev'; Meta=@{ a=@{ b=@{ c=1 } } } }
(Invoke-RestMethod "$base/api/servers" -Method Post -Body ($o | ConvertTo-Json -Depth 10) -ContentType 'application/json').Meta.a.b.c
Scenario analysis
A teammate's script prints “HTTP 404” in CI but the job is green, and the next step fails with “null-valued expression”. What happened and what would you change?

The script called Invoke-RestMethod without handling the error; the statement failed, the script continued (no $ErrorActionPreference = 'Stop'), and the job's exit code came from the last command. The variable stayed $null. Change: decide explicitly — -SkipHttpErrorCheck -StatusCodeVariable with a switch, or try/catch that rethrows non-404 errors — and make the script exit 1 (or throw) on unexpected statuses so CI turns red at the real cause.

Verified teaching videos

▶
Call REST APIs with Invoke-RestMethod in PowerShell — Adam Driscoll
English · REST basics, methods, headers and JSON with Invoke-RestMethod
▶
PowerShell Quick Tips : Invoke-RestMethod vs Invoke-WebRequest (Calling Rest APIs) — JackedProgrammer
English · short comparison of the two cmdlets

Official documentation

Video storyboard (about 90 seconds)

These materials cannot generate video or MP3 directly; the storyboard and narration are provided for a video tool.

Shot 1 · 0–20s
Visual: one request arrow, a response splits into two boxes: “IRM → objects”, “IWR → status, headers, content”.
Narration: same request, different gift wrapping.
Shot 2 · 20–45s
Visual: a nested hashtable; level 3 turns into the text System.Collections.Hashtable with a small yellow warning.
Narration: always pass Depth when you send JSON.
Shot 3 · 45–70s
Visual: a 404 bursts through a “SilentlyContinue” umbrella.
Narration: HTTP errors are terminating. Catch them, or skip the check and read the status.
Shot 4 · 70–90s
Visual: switch statement: 200 → data, 404 → null, else → throw.
Narration: turn every status code into a decision.
or score ≥ 70% on the Quiz

Module 2 · Real APIs: pagination, retries, rate limits and timeouts

06:00 – 13:00 · Production APIs return data in pages, fail transiently, throttle you and sometimes hang. Built-in parameters cover part of it — this module measures exactly which part on 7.6.10, then writes the rest.
7 minMock API · real timings★★★★★
Learning objectives
  • Collect all pages with -FollowRelLink (RFC 8288 Link header) or a nextLink / NextToken loop, and cap them with -MaximumFollowRelLink.
  • State what -MaximumRetryCount / -RetryIntervalSec retry on 7.6: every 4xx/5xx status (including 404, and also for POST), with Retry-After honored on 429 — but not timeouts or refused connections.
  • Handle 429 deliberately: read Retry-After, back off, reduce concurrency.
  • Choose between -ConnectionTimeoutSeconds (alias -TimeoutSec, the whole wait for a response) and -OperationTimeoutSeconds (stalls while reading the response stream).
Prerequisites: Module 1. Importance:★★★★★ (the core animation of this lesson)

What: three facts of life for API clients

FactHow APIs express itClient duty
Lists are pagedLink: <url>; rel="next" header (GitHub, the mock API), nextLink / @odata.nextLink in the body (Azure, Graph), NextToken / ContinuationToken (AWS), $skipToken (Resource Graph)Loop until the token is empty; never assume page 1 is everything
Failures are often transient408, 500, 502, 503, 504; dropped connectionsRetry a few times with growing waits; only for idempotent requests unless the API supports idempotency keys
You will be throttled429 Too Many Requests (sometimes 503) + Retry-After: <seconds or HTTP date>; Azure Resource Manager and AWS also return remaining-quota headersWait at least Retry-After; slow down globally

Why: measured behavior of the built-in retry (7.6.10)

Situation (-MaximumRetryCount 3 -RetryIntervalSec 1)Retried?Evidence below
503 twice, then 200Yes — succeeded on attempt 3 after 2.1 sCommands, block 4
404 (permanent)Yes — 3 attempts, 2.0 s wastedBlock 5
429 with Retry-After: 3Yes — waited 3 s, not 1 s: “Retrying after interval of 3 seconds”Block 6
POST to an endpoint returning 503Yes — a non-idempotent request was sent 3 timesBlock 11
Timeout (-TimeoutSec reached)No — fails immediately with ConnectionTimeoutReached (with -MaximumRetryCount 2: one attempt, 1.0 s)Block 8; animation “timeout”
Connection refused / DNS failureNoBlock 10

So the built-in retry is too eager (404s, POSTs) and too narrow (no network errors) at the same time. It is fine for a quick GET; libraries should classify statuses themselves — which is exactly what OpsKit's Invoke-OpsApi does in Module 8.

How: backoff

Wait base × 2^(attempt−1) (0.5, 1, 2, 4 s …), cap it, add jitter when many clients retry at once (so they do not hit the server in lockstep), and let Retry-After override the computed delay. Stop after a small number of attempts and fail with a message that includes the URL, the last status and the attempt count.

When: which timeout?

ParameterMeaning (verified)Use it for
-ConnectionTimeoutSeconds / -TimeoutSecSets HttpClient.Timeout: connect + send + wait for the response headers. A server that sleeps 4 s fails a 2 s limit with ConnectionTimeoutReachedEvery call in automation (the default is 100 s)
-OperationTimeoutSecondsLimits the time between reads of the response stream. A server that waits 3 s before answering was not cut off by a 1 s operation timeoutLarge downloads and streaming responses that may stall halfway
Common misconceptions① “-MaximumRetryCount retries only transient errors” — it retries every 4xx/5xx, including 404 and POST. ② “It also retries network failures” — refused connections and timeouts are not retried. ③ “-FollowRelLink returns one flat list” — it returns one result per page; take .value (member enumeration) to flatten. ④ “-OperationTimeoutSeconds limits the whole call” — it does not limit waiting for the first byte. ⑤ “Retrying faster recovers faster” — on 429 it makes the throttling longer.

Sequence: a paginated, retried call

Client (pwsh) API GET ?page=1 200 · value[5] · nextLink=page 2 GET ?page=2 503 Service Unavailable wait 0.5 s (backoff) GET ?page=2 (attempt 2) 200 · value[5] · nextLink=page 3 GET ?page=3 429 Too Many Requests · Retry-After: 1 wait 1 s (Retry-After wins) GET ?page=3 (attempt 2) 200 · value[2] · nextLink=null → done (12 items)
Figure 7-3: the shape of the integrated lab's API read — this exact sequence (a 429 on page 2) appears in its verbose log

Decision: retry or not?

Response or exception 2xx / 3xxsuccess → next pageor return Transient408 · 429 · 500 · 502 · 503 · 504timeout · refused · reset→ wait (Retry-After or backoff), retryonly if the method is safe to repeat Permanent400 · 401 · 403 · 404409 · 422→ fail now with theAPI's error message
Figure 7-4: the classification Invoke-OpsApi implements; the built-in -MaximumRetryCount treats everything ≥ 400 as “transient” and network errors as “permanent”

Core animation: a paginated, retried API call

Each scenario is a real run from the Commands tab or Module 8. Watch which attempts are made, how long the client waits, and where it stops.

Ready.
Real mechanism behind the animation In WebRequestPSCmdlet, the retry loop runs around the send: if the status code is not a success and retries remain, it waits RetryIntervalSec — or, for 429 with a Retry-After delta, that value — writes “Retrying after interval of N seconds” to the verbose stream and sends the request again. Exceptions thrown by HttpClient (timeouts, socket errors) leave the loop immediately. -FollowRelLink is a second loop outside it that parses the Link header after each successful page.

Command table

Command / parameterPurposeNotes (verified 7.6.10)
-FollowRelLink [-MaximumFollowRelLink n]Follow Link: rel="next"One output per page; n counts pages including the first
while ($uri) { $r = irm $uri; $r.value; $uri = $r.nextLink }Body-based pagingAzure, Graph ('@odata.nextLink'), the mock API
-MaximumRetryCount n -RetryIntervalSec sBuilt-in retryAll ≥ 400 statuses; 429 honors Retry-After; no retry on exceptions
$_.Exception.Response.Headers.RetryAfterRead Retry-After in catch.Delta (TimeSpan) or .Date
-ResponseHeadersVariable h; $h['Retry-After']Same, without exceptionsWith -SkipHttpErrorCheck
-ConnectionTimeoutSeconds (alias -TimeoutSec)Overall wait for a responseError id ConnectionTimeoutReached
-OperationTimeoutSecondsStall timeout while reading the bodyDoes not cap time-to-first-byte
[Diagnostics.Stopwatch]::StartNew()Measure what really happenedCheaper and more precise than Measure-Command around blocks

1–2. Pagination

$pages = Invoke-RestMethod "$base/api/servers?pageSize=5" -FollowRelLink
$pages.Count
$pages | ForEach-Object { 'page {0}: {1} items' -f $_.page, $_.value.Count }
$servers = $pages.value          # member enumeration flattens the pages
$servers.Count
@((Invoke-RestMethod "$base/api/servers?pageSize=5" -FollowRelLink -MaximumFollowRelLink 2).value).Count
3
page 1: 5 items
page 2: 5 items
page 3: 2 items
12
10
$uri = "$base/api/servers?pageSize=5&env=prod"
$all = while ($uri) {
    $resp = Invoke-RestMethod $uri
    $resp.value                 # emit this page's items
    $uri  = $resp.nextLink      # $null on the last page ends the loop
}
$all.Count
$all.Name -join ', '
6
web-01, web-02, api-01, edge-01, db-01, bastion-01

3–4. Transient 503: without and with the built-in retry

try { Invoke-RestMethod "$base/flaky?key=a" } catch { [int]$_.Exception.Response.StatusCode }

$sw = [Diagnostics.Stopwatch]::StartNew()
Invoke-RestMethod "$base/flaky?key=b" -MaximumRetryCount 3 -RetryIntervalSec 1 -Verbose
'{0:n1}s' -f $sw.Elapsed.TotalSeconds
503
VERBOSE: WebRequest: v1.1 GET http://127.0.0.1:5050/flaky with query length 5
VERBOSE: WebResponse: 503 Service Unavailable with application/json payload with body size 74 B (74 bytes)
VERBOSE: Retrying after interval of 1 seconds. Status code for previous attempt: ServiceUnavailable
VERBOSE: WebRequest: v1.1 GET http://127.0.0.1:5050/flaky with query length 5
VERBOSE: WebResponse: 503 Service Unavailable with application/json payload with body size 74 B (74 bytes)
VERBOSE: Retrying after interval of 1 seconds. Status code for previous attempt: ServiceUnavailable
VERBOSE: WebRequest: v1.1 GET http://127.0.0.1:5050/flaky with query length 5
VERBOSE: WebResponse: 200 OK with application/json payload with body size 27 B (27 bytes)

status attempt
------ -------
ok           3

2.1s

5. A 404 is retried too

$sw.Restart()
try { Invoke-RestMethod "$base/api/servers/prod/web-99" -MaximumRetryCount 2 -RetryIntervalSec 1 -Verbose }
catch { '404 after {0:n1}s' -f $sw.Elapsed.TotalSeconds }
VERBOSE: WebRequest: v1.1 GET http://127.0.0.1:5050/api/servers/prod/web-99
VERBOSE: WebResponse: 404 Not Found with application/json payload with body size 77 B (77 bytes)
VERBOSE: Retrying after interval of 1 seconds. Status code for previous attempt: NotFound
VERBOSE: WebRequest: v1.1 GET http://127.0.0.1:5050/api/servers/prod/web-99
VERBOSE: WebResponse: 404 Not Found with application/json payload with body size 77 B (77 bytes)
VERBOSE: Retrying after interval of 1 seconds. Status code for previous attempt: NotFound
VERBOSE: WebRequest: v1.1 GET http://127.0.0.1:5050/api/servers/prod/web-99
VERBOSE: WebResponse: 404 Not Found with application/json payload with body size 77 B (77 bytes)
404 after 2.0s

6–7. 429 and Retry-After

$sw.Restart()
Invoke-RestMethod "$base/ratelimit?key=a&after=3" -MaximumRetryCount 2 -RetryIntervalSec 1 -Verbose
'{0:n1}s' -f $sw.Elapsed.TotalSeconds

try { Invoke-RestMethod "$base/ratelimit?key=b" }
catch {
    $resp = $_.Exception.Response
    [int]$resp.StatusCode
    $resp.Headers.RetryAfter.Delta.TotalSeconds
}
VERBOSE: WebRequest: v1.1 GET http://127.0.0.1:5050/ratelimit with query length 13
VERBOSE: WebResponse: 429 Too Many Requests with application/json payload with body size 69 B (69 bytes)
VERBOSE: Retrying after interval of 3 seconds. Status code for previous attempt: TooManyRequests
VERBOSE: WebRequest: v1.1 GET http://127.0.0.1:5050/ratelimit with query length 13
VERBOSE: WebResponse: 200 OK with application/json payload with body size 27 B (27 bytes)

status attempt
------ -------
ok           2

3.0s
429
2

8–9. Timeouts

$sw.Restart()
try { Invoke-RestMethod "$base/slow?sec=4" -TimeoutSec 2 }
catch { $_.FullyQualifiedErrorId; $_.Exception.Message; '{0:n1}s' -f $sw.Elapsed.TotalSeconds }
Start-Sleep -Seconds 3      # the single-threaded mock is still busy with /slow

(Get-Command Invoke-RestMethod).Parameters['ConnectionTimeoutSeconds'].Aliases
$sw.Restart()
$r = Invoke-RestMethod "$base/slow?sec=3" -OperationTimeoutSeconds 1
"$($r.status) after {0:n1}s" -f $sw.Elapsed.TotalSeconds
ConnectionTimeoutReached,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
The request was canceled due to the configured HttpClient.Timeout of 2 seconds elapsing.
2.0s
TimeoutSec
ok after 3.0s

10–12. What is not retried, and what should not be

$sw.Restart()
try { Invoke-RestMethod http://127.0.0.1:5999/health -MaximumRetryCount 3 -RetryIntervalSec 1 }
catch { $_.Exception.Message; 'no retry: {0:n1}s' -f $sw.Elapsed.TotalSeconds }

$sw.Restart()
$p = Invoke-RestMethod "$base/flaky?key=post" -Method Post -MaximumRetryCount 3 -RetryIntervalSec 1
"POST succeeded on attempt $($p.attempt) after {0:n1}s" -f $sw.Elapsed.TotalSeconds

Invoke-RestMethod "$base/stats"
No connection could be made because the target machine actively refused it. (127.0.0.1:5999)
no retry: 1.0s
POST succeeded on attempt 3 after 2.0s

requests : 23
e401     : 0
e429     : 2
e503     : 5
secure   : 0

How to verify: the mock's /stats counts what the server really saw — 5 × 503 and 2 × 429 for the client's “just a few calls”. Common mistake: adding -MaximumRetryCount 5 to a POST that creates something; if the server created the item and then failed to answer, you create it again. Production use: for GETs in scripts, -MaximumRetryCount 3 -RetryIntervalSec 2 -TimeoutSec 30 is a reasonable default; in modules, use a wrapper that retries only transient statuses and network errors, honors Retry-After, and retries writes only with an idempotency key or a known-safe PUT.

Goal: Build a small paging + retry loop by hand and compare it with the built-in parameters. Environment: mock API running. Cost: none.

Count all servers with -FollowRelLink and with a nextLink loop; both must say 12:
$a = @((Invoke-RestMethod "$base/api/servers?pageSize=4" -FollowRelLink).value).Count
$b = 0; $u = "$base/api/servers?pageSize=4"
while ($u) { $r = Invoke-RestMethod $u; $b += @($r.value).Count; $u = $r.nextLink }
"$a $b"
12 12
Write a retry loop that only retries transient statuses:
function Invoke-LabGet([string]$Uri, [int]$Max = 4) {
    for ($i = 1; ; $i++) {
        $r = Invoke-RestMethod $Uri -SkipHttpErrorCheck -StatusCodeVariable sc -ResponseHeadersVariable h
        if ($sc -lt 400) { return $r }
        if ($sc -notin 408, 429, 500, 502, 503, 504 -or $i -gt $Max) { throw "HTTP $sc after $i attempt(s)" }
        $wait = if ($h['Retry-After']) { [int]$h['Retry-After'][0] } else { [math]::Pow(2, $i - 1) / 2 }
        Write-Verbose "attempt $i -> $sc, waiting $wait s" -Verbose
        Start-Sleep -Milliseconds (1000 * $wait)
    }
}
Invoke-LabGet "$base/flaky?key=lab1"
try { Invoke-LabGet "$base/api/servers/prod/nope" } catch { $_.Exception.Message }
VERBOSE: attempt 1 -> 503, waiting 0.5 s
VERBOSE: attempt 2 -> 503, waiting 1 s

status attempt
------ -------
ok           3

HTTP 404 after 1 attempt(s)
Prove that Retry-After wins: time Invoke-LabGet "$base/ratelimit?key=lab2&after=2" with a Stopwatch; it should take about 2 s, not 0.5 s.
Timeout budget: call /slow?sec=3 with -TimeoutSec 1 inside your function's Invoke-RestMethod, observe that the exception escapes your status-code logic, then add a try/catch that treats ConnectionTimeoutReached as transient. (Wait 3 s afterwards: the mock is single-threaded.)
Cleanup: Remove-Item function:Invoke-LabGet; keep the API running.

Case 1: the report that always had exactly 1,000 VMs

Problem: A monthly VM report showed 1,000 rows every month while the estate grew. Root cause: the script read one page of a REST list (and of Resource Graph, which returns at most 1,000 rows per call) and ignored nextLink / $skipToken. Fix: loop until the continuation token is empty; add an assertion that compares the row count with the API's count/totalRecords when the API returns one.

Case 2: retries turned a throttle into an outage

Problem: 40 parallel runbooks hit the same API; on 429 each retried every second. The API's throttle window kept extending and every runbook failed for 20 minutes. Root cause: fixed short retry interval, ignored Retry-After, no global concurrency limit. Fix: honor Retry-After, exponential backoff with jitter, and -ThrottleLimit on the parallel loop (Lesson 6). The built-in 7.x retry already honors Retry-After on 429 — which is better than many hand-written loops.

Case 3: duplicate tickets after a gateway timeout

Problem: An incident tool sometimes opened two identical tickets. Root cause: Invoke-RestMethod -Method Post -MaximumRetryCount 3; the gateway returned 504 after the backend had already created the ticket, and the retry created a second one. Fix: no automatic retries for POST, or send an idempotency key header supported by the API; for retries, first GET to check whether the item exists (get-then-set, Module 6).

Common errors and fixes

Response status code does not indicate success: 429 (Too Many Requests)
catch { $_.Exception.Response.Headers.RetryAfter }   # Delta or Date

Fix: wait at least that long; reduce parallelism; spread schedules (not every job at :00).

The request was canceled due to the configured HttpClient.Timeout of N seconds elapsing

Cause: -TimeoutSec/-ConnectionTimeoutSeconds reached (default 100 s). Fix: raise it for known slow endpoints, or use async APIs (202 Accepted + polling a status URL). Not retried by -MaximumRetryCount.

My loop never ends

Cause: wrong property name (nextLink vs '@odata.nextLink' vs NextToken), or the API returns an empty string instead of null and the URL repeats.

$seen = @{}; while ($uri -and -not $seen[$uri]) { $seen[$uri] = 1; … }
-FollowRelLink only returned the first page

Cause: the API puts the next link in the body, not in a Link header. -FollowRelLink only reads rel="next" headers. Fix: write the loop.

Retries make a broken call take minutes

Cause: 401/403/404 retried by -MaximumRetryCount. Fix: classify statuses yourself (-SkipHttpErrorCheck), or keep the built-in count small.

Command-line exercises
1. Return all prod servers from the mock API in one array, using the body's nextLink, with page size 2.
$u = "$base/api/servers?env=prod&pageSize=2"
$prod = while ($u) { $r = Invoke-RestMethod $u; $r.value; $u = $r.nextLink }
$prod.Count   # 6
2. Print the Retry-After value of a 429 without using try/catch.
$null = Invoke-RestMethod "$base/ratelimit?key=q2" -SkipHttpErrorCheck -StatusCodeVariable sc -ResponseHeadersVariable h
"$sc $($h['Retry-After'])"
Scenario analysis
An Azure Function calls a partner API with -MaximumRetryCount 5 -RetryIntervalSec 10. When the partner's certificate expires, the function times out after 5 minutes instead of failing fast. Explain and fix.

A TLS failure is an exception, which is not retried — so that is not the cause. More likely the partner answers 4xx/5xx (e.g., a 495/525 from its gateway or 401), which is retried 5 × 10 s, plus each attempt waits up to -TimeoutSec (default 100 s). Fix: classify statuses (retry only 408/429/5xx), set a short -TimeoutSec, cap total elapsed time, and log the status and ErrorDetails of the last attempt so the alert shows the real cause.

Verified teaching videos

▶
Call REST APIs with Invoke-RestMethod in PowerShell — Adam Driscoll
English · status codes, headers and query strings; background for this module

No verified video was found that covers -FollowRelLink, the exact 7.x retry rules or -OperationTimeoutSeconds; rely on this module's measured runs and the documentation.

Official documentation

Video storyboard (about 90 seconds)

These materials cannot generate video or MP3 directly; the storyboard and narration are provided for a video tool.

Shot 1 · 0–20s
Visual: three pages slide in, a “nextLink” arrow chains them, the last arrow is null.
Narration: one page is never everything. Follow the link until it is empty.
Shot 2 · 20–50s
Visual: the sequence diagram: 503 → wait → 200; 429 → Retry-After 1 → 200.
Narration: retry transient failures, and let Retry-After decide how long to wait.
Shot 3 · 50–75s
Visual: a table with check marks: 404 retried, POST retried, timeout not retried.
Narration: the built-in retry is too eager and too narrow at the same time.
Shot 4 · 75–90s
Visual: two stopwatches: “time to first byte” vs “stall while reading”.
Narration: TimeoutSec caps the wait for the response; OperationTimeoutSeconds catches a stalled stream.
or score ≥ 70% on the Quiz

Module 3 · Authentication and secrets: tokens, SecretManagement and SecretStore

13:00 – 21:00 · A bearer token is a password with an expiry date. This module keeps it out of scripts, history, logs and plain HTTP; stores long-lived secrets in a vault through one API; and removes secrets from CI entirely with managed identities and OIDC federation.
8 minMock API · real outputsVault steps: Expected output★★★★★
Learning objectives
  • Send a bearer token with -Authentication Bearer -Token <SecureString>, and understand why PowerShell refuses to send it over plain HTTP without -AllowUnencryptedAuthentication.
  • Know where a token may live: environment variable injected by CI, SecretManagement vault, managed identity — and where it must never live: script files, repository, PSReadLine history, verbose logs.
  • Use the SecretManagement API (Get-Secret, Set-Secret, Get-SecretInfo, Register-SecretVault) and configure the SecretStore vault for interactive and unattended use.
  • Explain managed identity and workload identity federation (OIDC) for GitHub Actions / Azure DevOps, and why they beat stored client secrets.
Prerequisites: Modules 1–2. Importance:★★★★★ (a leaked token is the most expensive bug in this lesson)

What: kinds of credentials an automation script meets

CredentialLifetimeExampleWhere it should come from
Bearer access tokenMinutes to hoursEntra ID token for ARM (Get-AzAccessToken), GitHub token, the mock API's lab-token-7f3aRequested at run time from an identity; never stored
API key / PAT / client secretMonthsA SaaS API key, a service principal secretA vault (Key Vault, SecretStore, CI secret store) → environment variable or Get-Secret
Certificate1–2 yearsService principal certificateCertificate store / Key Vault, referenced by thumbprint
Managed identityNo secret at allAzure VM, Function, Automation account; AWS instance profile / task roleThe platform's metadata endpoint
Federated (OIDC) tokenMinutes, per jobGitHub Actions id-token: write exchanged for an Azure or AWS tokenThe CI provider, trusted by the cloud

Why: three verified ways a token leaks in PowerShell

LeakVerified behavior (7.6.10, PSReadLine 2.4.5)Defense
Command history filePSReadLine's default history handler keeps lines containing token, password, asplaintext, secret, apikey in memory only — but irm $u -Headers @{ Authorization = 'Bearer eyJ…' } and $env:OPSKIT_KEY = 'eyJ…' were saved to the history fileNever type secrets; load them (Get-Secret, env var set by CI)
Plain HTTP-Authentication Bearer over http:// fails with WebCmdletAllowUnencryptedAuthenticationRequiredExceptionUse HTTPS; allow the override only for loopback (OpsKit does this)
Output and logsConvertFrom-SecureString -AsPlainText prints the token; a SecureString prints only its type nameKeep tokens as SecureString until the last moment; never Write-Verbose a header

How: SecretManagement in one picture

Microsoft.PowerShell.SecretManagement is an abstraction: one set of cmdlets (Get-Secret, Set-Secret, Get-SecretInfo, Remove-Secret) over any number of registered vault extensions — Microsoft.PowerShell.SecretStore (a local encrypted file, cross-platform), Az.KeyVault, KeePass, 1Password, HashiCorp Vault, and others from the Gallery. Scripts call Get-Secret -Name OpsKitApiToken; which vault answers is configuration, not code. Secrets come back as SecureString by default (-AsPlainText only when an API truly needs a string).

SecretStore setting (verified enums)ValuesInteractive laptopUnattended job
-AuthenticationNone, PasswordPasswordPassword, unlocked with Unlock-SecretStore from a protected source
-InteractionNone, PromptPromptNone (a prompt would hang the job)
-PasswordTimeoutseconds900Long enough for the run
-ScopeCurrentUser, AllUsersCurrentUser (the store is per user; a service account has its own)

When: pick by where the code runs

Runs onBest optionAcceptableAvoid
Your laptopInteractive sign-in (Az/AWS SSO); SecretStore for API keysEnv var set for one sessionKeys in $PROFILE
Azure VM, Function, AutomationManaged identity (Connect-AzAccount -Identity); Key Vault for third-party keysCertificateClient secrets in app settings
GitHub Actions / Azure DevOpsOIDC federation (no stored cloud secret)Repository/environment secret → env varSecrets echoed in logs, set -x-style tracing (Set-PSDebug -Trace)
AWS EC2 / ECS / LambdaInstance profile / task roleSSO profile on a jump hostAccess keys in ~/.aws/credentials on servers
Common misconceptions① “SecureString encrypts my token for the network” — it only protects it in memory/at rest on Windows (DPAPI); on Linux/macOS a SecureString is not encrypted in memory. The wire is protected only by HTTPS. ② “PSReadLine never saves secrets” — its filter is a keyword heuristic; a raw JWT in a header line is saved. ③ “-AllowUnencryptedAuthentication is harmless in a lab” — it is a habit that ends in production; scope it to loopback. ④ “SecretStore is a server” — it is a per-user encrypted file. ⑤ “A service principal secret in the CI secret store is as good as OIDC” — it never expires by itself and works from anywhere; federated credentials are bound to a repository, branch or environment.

Where the token comes from

SecretManagementGet-Secret OpsKitApiToken CI secret → env var$env:OPSKIT_API_TOKEN Managed identitymetadata endpoint → token OIDC (GitHub id-token)exchange → cloud token SecureStringnever printed, never loggedConvertTo-SecureString once -Authentication Bearer -Tokenhttps:// → Authorization headerhttp:// → refused, unless-AllowUnencryptedAuthentication(OpsKit: loopback only) Neverin .ps1 files or Gittyped at the prompt (history)in Write-Verbose / transcripts
Figure 7-5: four acceptable sources, one in-memory form, one way out (HTTPS), and the places tokens must never be

SecretManagement architecture

Your script / OpsKitGet-Secret -Name X SecretManagement 1.1registry of vaults (per user)default vault · metadataSecureString / PSCredential /Hashtable / byte[] / string SecretStore (local encrypted file) Az.KeyVault (Azure Key Vault) other extensions (KeePass, 1Password …)
Figure 7-6: the script depends on the API, not on the vault; you can move from SecretStore on a laptop to Key Vault in Azure without changing code

Where does the token come from?

Step through how each setup gets a credential into an API call, and where it breaks.

Ready.
Real mechanism behind the animation With -Authentication Bearer, the web cmdlets convert the SecureString to text only when building the Authorization: Bearer … header, and they refuse to do so for a non-HTTPS URI unless -AllowUnencryptedAuthentication is present. PSReadLine decides per line with AddToHistoryHandler: its default returns MemoryOnly when the line matches a sensitive-word pattern, otherwise MemoryAndFile. Managed identity and OIDC never put a long-lived secret on disk: the platform issues a short-lived token on request.

Command table

CommandPurposeNotes
-Authentication Bearer -Token $ssSend a bearer token-Token is [SecureString]; a string fails to bind
-AllowUnencryptedAuthenticationAllow credentials over httpLoopback labs only
ConvertTo-SecureString $s -AsPlainText -ForceWrap a string you received (env var)Do it once, at the edge
Get-Secret -Name n [-Vault v] [-AsPlainText]Read a secretSecureString by default
Set-Secret -Name n -Secret $v [-Metadata @{}]Store or update-NoClobber to refuse overwrites; supports -WhatIf
Get-SecretInfo [-Name *]List names, types, metadataNever returns values
Register-SecretVault -Name v -ModuleName Microsoft.PowerShell.SecretStore -DefaultVaultAdd a vaultPer user; once per machine
Set-SecretStoreConfiguration -Authentication Password -Interaction None -PasswordTimeout 3600Unattended storeThen Unlock-SecretStore -Password $p
(Get-PSReadLineOption).AddToHistoryHandlerHistory filterTest a line before you type it

1. No token, then a token over plain HTTP

try { Invoke-RestMethod "$base/api/secure/servers" }
catch {
    [int]$_.Exception.Response.StatusCode
    $_.Exception.Response.Headers.WwwAuthenticate.ToString()
}
$env:OPSKIT_API_TOKEN = 'lab-token-7f3a'          # in CI this comes from the pipeline's secret store
$token = ConvertTo-SecureString $env:OPSKIT_API_TOKEN -AsPlainText -Force
try { Invoke-RestMethod "$base/api/secure/servers" -Authentication Bearer -Token $token }
catch { $_.FullyQualifiedErrorId; $_.Exception.Message }
401
Bearer realm="pslab"
WebCmdletAllowUnencryptedAuthenticationRequiredException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
The cmdlet cannot protect plain text secrets sent over unencrypted connections. To suppress this warning and send plain text secrets over unencrypted networks, reissue the command specifying the AllowUnencryptedAuthentication parameter.

2. Allowed for the loopback lab API

$r = Invoke-RestMethod "$base/api/secure/servers?pageSize=3" -Authentication Bearer -Token $token -AllowUnencryptedAuthentication
$r.count; $r.value | Format-Table Name, Env, IP

try { Invoke-RestMethod "$base/api/secure/servers" -Authentication Bearer -Token 'lab-token-7f3a' -AllowUnencryptedAuthentication }
catch { $_.Exception.Message }
12

Name   Env IP
----   --- --
web-01 dev 10.10.1.21
api-01 dev 10.10.1.22
db-01  dev 10.10.1.23

Cannot bind parameter 'Token'. Cannot convert the value of type "System.String" to type "System.Security.SecureString".

3. What a SecureString shows — and how to defeat it

"$token"
$token.Length
ConvertFrom-SecureString $token -AsPlainText     # never in real code paths that log
System.Security.SecureString
14
lab-token-7f3a

4. Would this line be saved to the history file?

$h = (Get-PSReadLineOption).AddToHistoryHandler
$lines = @(
    '$t = ConvertTo-SecureString $plain -AsPlainText -Force'
    '$env:OPSKIT_API_TOKEN = ''lab-token-7f3a'''
    'irm $u -Headers @{ Authorization = ''Bearer eyJ0eXAiOiJKV1Qi.e30.sig'' }'
    '$env:OPSKIT_KEY = ''eyJ0eXAiOiJKV1Qi.e30.sig'''
    'Connect-AzAccount -ServicePrincipal -Credential $cred -Tenant $tid'
)
foreach ($l in $lines) { '{0,-13} {1}' -f $h.Invoke($l), $l }
(Get-PSReadLineOption).HistorySavePath
MemoryOnly    $t = ConvertTo-SecureString $plain -AsPlainText -Force
MemoryOnly    $env:OPSKIT_API_TOKEN = 'lab-token-7f3a'
MemoryAndFile irm $u -Headers @{ Authorization = 'Bearer eyJ0eXAiOiJKV1Qi.e30.sig' }
MemoryAndFile $env:OPSKIT_KEY = 'eyJ0eXAiOiJKV1Qi.e30.sig'
MemoryAndFile Connect-AzAccount -ServicePrincipal -Credential $cred -Tenant $tid
C:\Users\labadmin\AppData\Roaming\Microsoft\Windows\PowerShell\PSReadLine\ConsoleHost_history.txt

The last line is fine (no secret on it). The two MemoryAndFile lines with a JWT would sit in plain text in that file. If it happened: rotate the token, then remove the line from the file.

5. SecretManagement and SecretStore: the commands (metadata from the real modules)

Get-Command -Module Microsoft.PowerShell.SecretManagement | Sort-Object Name | ForEach-Object Name | Join-String -Separator ', '
Get-Command -Module Microsoft.PowerShell.SecretStore | Sort-Object Name | ForEach-Object Name | Join-String -Separator ', '
Get-Command Get-Secret, Set-Secret -Syntax
Get-Secret, Get-SecretInfo, Get-SecretVault, Register-SecretVault, Remove-Secret, Set-Secret, Set-SecretInfo, Set-SecretVaultDefault, Test-SecretVault, Unlock-SecretVault, Unregister-SecretVault
Get-SecretStoreConfiguration, Reset-SecretStore, Set-SecretStoreConfiguration, Set-SecretStorePassword, Unlock-SecretStore

Get-Secret [-Name] <string> [[-Vault] <string>] [-AsPlainText] [<CommonParameters>]

Get-Secret -InputObject <SecretInformation> [-AsPlainText] [<CommonParameters>]

Set-Secret [-Name] <string> [-SecureStringSecret] <securestring> [[-Vault] <string>] [[-Metadata] <hashtable>] [-NoClobber] [-WhatIf] [-Confirm] [<CommonParameters>]

Set-Secret [-Name] <string> [-Secret] <Object> [[-Vault] <string>] [[-Metadata] <hashtable>] [-NoClobber] [-WhatIf] [-Confirm] [<CommonParameters>]

Set-Secret [-SecretInfo] <SecretInformation> -Vault <string> [-NoClobber] [-WhatIf] [-Confirm] [<CommonParameters>]

6. Register a SecretStore vault and use it (on your own machine)

Register-SecretVault -Name LabStore -ModuleName Microsoft.PowerShell.SecretStore -DefaultVault
Set-Secret -Name OpsKitApiToken -Secret (Read-Host 'API token' -AsSecureString) -Metadata @{ purpose = 'pslab mock API' }
Get-SecretVault
Get-SecretInfo -Name OpsKit* | Format-Table Name, Type, VaultName
(Get-Secret -Name OpsKitApiToken).GetType().Name
Creating a new LabStore vault. A password is required by the current store configuration.
Enter password:
********
Enter password again for verification:
********
API token: **************

Name     ModuleName                       IsDefaultVault
----     ----------                       --------------
LabStore Microsoft.PowerShell.SecretStore True

Name           Type         VaultName
----           ----         ---------
OpsKitApiToken SecureString LabStore

SecureString

7. Unattended SecretStore (scheduled task / service account)

# One-time setup as the service account. The store password itself must come from a protected source
# (DPAPI-protected file via Export-Clixml on Windows, Key Vault, the CI secret store) — not from the script.
$storePw = Import-Clixml -Path C:\jobs\secrets\storepw.xml     # SecureString, readable only by this account on this machine
Set-SecretStoreConfiguration -Scope CurrentUser -Authentication Password -Interaction None `
    -PasswordTimeout 3600 -Password $storePw -Confirm:$false
# Every run:
Unlock-SecretStore -Password $storePw
$token = Get-Secret -Name OpsKitApiToken
(no output on success; Get-Secret returns a SecureString)

8. CI: environment variable from the secret store, or no secret at all

# GitHub Actions — API key from an environment secret
- name: Sync inventory
  shell: pwsh
  env:
    OPSKIT_API_TOKEN: ${{ secrets.OPSKIT_API_TOKEN }}     # masked in logs by the runner
  run: ./scripts/Sync-OpsInventory.ps1

# Azure with OIDC federation — no Azure secret stored anywhere
permissions:
  id-token: write
  contents: read
steps:
  - uses: azure/login@v2
    with:
      client-id: ${{ vars.AZURE_CLIENT_ID }}
      tenant-id: ${{ vars.AZURE_TENANT_ID }}
      subscription-id: ${{ vars.AZURE_SUBSCRIPTION_ID }}
      enable-AzPSSession: true
  - shell: pwsh
    run: Get-AzContext | Select-Object Account, Subscription

How to verify: after a run, search the job log and ~/.../ConsoleHost_history.txt for the first 8 characters of the token — you should find nothing. Common mistake: Write-Verbose "Headers: $($headers | ConvertTo-Json)" while debugging — -Verbose in CI then prints the token (GitHub masks registered secrets, but not tokens your script derived from them). Production use: OpsKit's Get-OpsApiToken (Module 8) tries SecretManagement first, then $env:OPSKIT_API_TOKEN, returns a SecureString and only ever logs where the token came from.

Goal: Call the secure endpoint without the token ever appearing in a script, history or output. Environment: mock API running; SecretManagement optional. Cost: none.

Set the token for this session from a prompt, not from a literal (so neither the script nor history contains it):
$env:OPSKIT_API_TOKEN = Read-Host 'Mock API token (lab-token-7f3a)' -MaskInput

-MaskInput (PowerShell 7.1+) shows asterisks but returns a string — suitable for an env var.

Call the secure endpoint the safe way:
$tok = ConvertTo-SecureString $env:OPSKIT_API_TOKEN -AsPlainText -Force
$r = Invoke-RestMethod "$base/api/secure/servers?pageSize=50" -Authentication Bearer -Token $tok -AllowUnencryptedAuthentication
$r.value | Group-Object Env -NoElement
Count Name
----- ----
    3 dev
    6 prod
    3 staging
Check what history would keep: test three lines of your own with (Get-PSReadLineOption).AddToHistoryHandler.Invoke('…'). Find one that contains a secret but returns MemoryAndFile.
Optional, own machine only — SecretStore: run block 6 of the Commands tab, then (Get-Secret OpsKitApiToken -AsPlainText).Length should print 14. In Module 8, OpsKit will pick the secret up automatically.
Cleanup: Remove-Item Env:OPSKIT_API_TOKEN; if you registered the lab vault and want it gone: Remove-Secret OpsKitApiToken -Vault LabStore; Unregister-SecretVault LabStore.

Case 1: a PAT in a script, found by a secret scanner a year later

Problem: A repository's history contained $pat = 'ghp_…' in a “temporary” script. Root cause: testing with a literal, then committing. Deleting the line does not remove it from history. Fix: revoke the token first, then clean history if required; enable push protection / secret scanning; scripts read $env: or Get-Secret only. Add a PSScriptAnalyzer rule set (Lesson 8) that flags ConvertTo-SecureString -AsPlainText with a literal.

Case 2: a scheduled job that hung after a reboot

Problem: A nightly job using SecretStore ran for weeks, then hung forever after the server was patched. Root cause: the store was configured with -Interaction Prompt; after reboot it was locked and Get-Secret waited for a password nobody could type. Fix: -Interaction None for unattended stores (a locked store then throws), Unlock-SecretStore at the start of each run, and pwsh -NonInteractive (Lesson 1) so any prompt fails fast.

Case 3: expired client secret stops all deployments

Problem: All pipelines failed with AADSTS7000222: The provided client secret keys … are expired. Root cause: a service principal secret with a two-year expiry stored in 40 pipelines. Fix: move to workload identity federation (OIDC): no secret to expire or leak, and the trust is scoped to a repository and environment. Where secrets remain, store them in one place (Key Vault) with expiry alerts.

Common errors and fixes

The cmdlet cannot protect plain text secrets sent over unencrypted connections

Cause: -Authentication/-Credential with an http:// URI. Fix: use HTTPS. For a local test API only, add -AllowUnencryptedAuthentication.

Cannot bind parameter 'Token'. Cannot convert … "System.String" to type "System.Security.SecureString"
-Token (ConvertTo-SecureString $env:API_TOKEN -AsPlainText -Force)
401 Unauthorized although the token is right

Causes: token for the wrong audience/resource, expired token (check the exp claim), extra whitespace or a trailing newline from a file, or a redirect that dropped the header (-PreserveAuthorizationOnRedirect). WWW-Authenticate in the response often says which.

catch { $_.Exception.Response.Headers.WwwAuthenticate }
Get-Secret: There are currently no extension vaults registered

Cause: SecretManagement is installed but no vault is registered for this user (service accounts have their own registry). Fix: Register-SecretVault as that account, or fall back to an env var (OpsKit does).

A job hangs at Get-Secret

Cause: SecretStore is locked and configured to prompt. Fix: Set-SecretStoreConfiguration -Interaction None, Unlock-SecretStore at start, run with -NonInteractive.

Command-line exercises
1. Call the mock's secure endpoint with the token from $env:OPSKIT_API_TOKEN, in one line, without printing the token.
(Invoke-RestMethod "$base/api/secure/servers" -Authentication Bearer -Token (ConvertTo-SecureString $env:OPSKIT_API_TOKEN -AsPlainText -Force) -AllowUnencryptedAuthentication).count
2. List the names of all secrets whose metadata says purpose contains “pslab”, without reading any secret value.
Get-SecretInfo | Where-Object { $_.Metadata['purpose'] -like '*pslab*' } | Select-Object Name, VaultName
Scenario analysis
Your team runs a PowerShell runbook in Azure Automation that calls Azure APIs and a SaaS ticketing API. Today both credentials are variables in the Automation account. Propose a better design.

Azure: enable the Automation account's managed identity, grant it the minimum RBAC role at the right scope, and call Connect-AzAccount -Identity — no Azure secret remains. SaaS API key: store it in Key Vault, grant the managed identity Key Vault Secrets User on that vault, and read it at run time (Get-AzKeyVaultSecret -AsPlainText or SecretManagement with the Az.KeyVault extension). Log only which identity and secret name were used, set an expiry and an alert on the key, and rotate it without touching the runbook.

Verified teaching videos

▶
New PowerShell Secrets Management Module - Easily use any secret provider — John Savill's Technical Training
English · the SecretManagement idea and vault extensions (recorded around the preview/GA; check current versions)
▶
SecretManagement - Sydney Smith - PSConfEU 2022 — PowerShell Conference Europe
English · conference session from the PowerShell team
▶
How to Manage Secrets securely in PowerShell | Azure Key Vault — T-Minus365
English · Key Vault from PowerShell scripts

Official documentation

Video storyboard (about 90 seconds)

These materials cannot generate video or MP3 directly; the storyboard and narration are provided for a video tool.

Shot 1 · 0–20s
Visual: a token string travels from a script file to Git, to a history file and to a log — red marks on each.
Narration: a token is a password with an expiry date. Count the places it just leaked.
Shot 2 · 20–45s
Visual: four source boxes (vault, env var, managed identity, OIDC) feed one SecureString.
Narration: load it, keep it secure in memory, send it only over HTTPS.
Shot 3 · 45–70s
Visual: Get-Secret in the middle; SecretStore, Key Vault and KeePass plug in behind it.
Narration: code asks for a name; configuration decides which vault answers.
Shot 4 · 70–90s
Visual: a GitHub job requests an id-token; Azure answers with a short-lived access token; no secret on screen.
Narration: the best secret is the one you never store.
or score ≥ 70% on the Quiz

Module 4 · Az PowerShell: sign-in methods, contexts and read-only queries

21:00 – 28:00 · Az is a family of modules on top of Azure Resource Manager's REST API. Az.Accounts owns authentication and the context (account + tenant + subscription) that every other cmdlet silently uses. Most Azure automation accidents are context accidents.
7 minMetadata: real (Az 16.0.0)Cloud calls: Expected output★★★★☆
Learning objectives
  • Install Az modularly (Az.Accounts + the service modules you need) and check versions.
  • Pick a Connect-AzAccount parameter set for each situation: interactive, -UseDeviceAuthentication, -Identity, service principal with certificate, -FederatedToken.
  • Read and pin the context: Get-AzContext, Set-AzContext -Subscription, Disable-AzContextAutosave -Scope Process, a guard that stops on the wrong subscription.
  • Run read-only queries (Get-AzResourceGroup, Get-AzVM -Status) and preview changes with -WhatIf; compare Az objects with az CLI JSON text.
Prerequisites: Modules 1–3. Optional Azure sandbox. Importance:★★★★☆

What: the Az family

Module (version on the lab machine)Provides
Az.Accounts (5.5.0)Connect-AzAccount, contexts, token cache, Get-AzAccessToken, Invoke-AzRestMethod; required by all others
Az.Resources (10.0.0)Resource groups, generic resources, tags, deployments, RBAC
Az.Compute (11.6.0)VMs, disks, images, scale sets
Az.ResourceGraph (1.3.0)Search-AzGraph (Module 7)
Az (16.0.0 roll-up)Installs 102 modules; convenient on a workstation, wasteful in CI images and Functions

Why: the context is invisible state

After sign-in, Az stores a context: account, tenant, subscription, environment. Every cmdlet without -DefaultProfile uses it. By default contexts are saved to disk (~/.Azure) and shared by all your pwsh sessions — so Set-AzContext in one window changes the subscription of a script running in another. In automation: Disable-AzContextAutosave -Scope Process, sign in, select the subscription explicitly, and assert it.

How: Connect-AzAccount parameter sets (from Az.Accounts 5.5.0 metadata)

Parameter setMandatoryUse when
UserWithSubscriptionId—Interactive: browser or WAM on Windows; add -UseDeviceAuthentication on a remote shell without a browser
ManagedServiceLogin-IdentityAzure VM, Function, Automation, Container Apps; -AccountId <clientId> for a user-assigned identity
ServicePrincipalCertificateWithSubscriptionId-CertificateThumbprint -ApplicationId -TenantSelf-hosted runners / on-premises jobs (certificate in the store)
ServicePrincipalCertificateFileWithSubscriptionId-ApplicationId -Tenant -CertificatePathLinux/macOS with a PFX file
ClientAssertionParameterSet-ApplicationId -Tenant -FederatedTokenOIDC: a GitHub / Azure DevOps / Kubernetes token exchanged for an Azure token
ServicePrincipalWithSubscriptionId-Credential -ServicePrincipal -TenantClient secret (legacy; prefer certificate or federation)
AccessTokenWithSubscriptionId-AccessToken -AccountIdYou already have a token from elsewhere

When: Az PowerShell or Azure CLI?

Az PowerShellaz CLI from pwsh
Output.NET objects (PSResourceGroup, PSVirtualMachine)JSON text lines — verified: az version --output json returns Object[] of strings; pipe to ConvertFrom-Json
ErrorsError records (try/catch, -ErrorAction)stderr + $LASTEXITCODE (Lesson 5); $PSNativeCommandUseErrorActionPreference
-WhatIfYes on New-/Remove-/Set-/Update- cmdletsOnly some commands (az deployment … what-if)
Best forPowerShell pipelines, objects, OpsKitCopying examples from docs, bash parity
Common misconceptions① “Connect-AzAccount in my script picks the right subscription” — it picks a default (often the first one); always Set-AzContext. ② “Contexts are per window” — they are saved and shared by default. ③ “-WhatIf on Remove-AzResourceGroup is enough review” — it tells you the target, not what is inside it; list resources first. ④ “Install-Module Az is required” — install only what you use. ⑤ “Get-AzVM shows power state” — only with -Status (a slower, instance-view call).

From sign-in to a safe query

Sign-in methodinteractive / WAM-UseDeviceAuthentication-IdentitySP + certificate-FederatedToken (OIDC)SP + secret (legacy) Entra IDtoken formanagement.azure.com ContextAccountTenantSubscription ← Set-AzContextEnvironmentsaved to ~/.Azureunless Disable-AzContextAutosave Guarded queryassert SubscriptionIdGet-AzResourceGroupGet-AzVM -StatusSearch-AzGraphchanges: -WhatIf first No guard → the right script against the wrong subscriptionthe context silently defaulted, or another session changed it
Figure 7-7: authentication produces a token; the context decides where every following cmdlet acts

Sign-in method → context → query

Each scenario shows how a run authenticates, which subscription it ends up in, and whether the guard catches a mistake. Outputs here are Expected (no cloud sign-in on the lab machine).

Ready.
Real mechanism behind the animation Az.Accounts uses MSAL to obtain tokens and keeps them in a token cache; the context (an IAzureContextContainer) records which account, tenant and subscription to use. Each Az cmdlet takes -DefaultProfile; when omitted it uses the current context. With context autosave enabled, the context file is shared across sessions of the same user.

Command table

CommandPurposeNotes
Install-PSResource Az.Accounts, Az.Resources, Az.Compute -Scope CurrentUserModular installPin versions in CI (-Version '[10.0.0, 11.0.0)')
Connect-AzAccount -Tenant $t -Subscription $sInteractiveAdd -UseDeviceAuthentication without a browser
Connect-AzAccount -Identity [-AccountId $clientId]Managed identityAzure-hosted compute only
Connect-AzAccount -ServicePrincipal -ApplicationId $a -Tenant $t -CertificateThumbprint $thCertificate SPWindows cert store; -CertificatePath elsewhere
Connect-AzAccount -ApplicationId $a -Tenant $t -FederatedToken $jwtOIDCUsually done for you by azure/login
Get-AzContext / Set-AzContext -Subscription $idRead / pin contextUse the ID, not the name
Disable-AzContextAutosave -Scope ProcessKeep this run's context privateFirst line of automation
Get-AzResourceGroup [-Name] [-Tag @{owner='x'}]Read groupsRead-only
Get-AzVM [-ResourceGroupName] [-Status]VMs, with power state-Status adds instance view
New-/Remove-/Update-Az… -WhatIfPreviewVerified: these support ShouldProcess

1. What is installed (real metadata)

Get-Module -ListAvailable Az.Accounts, Az.Resources, Az.Compute, Az.ResourceGraph |
    Sort-Object Name, Version -Descending | Sort-Object Name -Unique | Format-Table Name, Version
Name             Version
----             -------
Az.Accounts      5.5.0
Az.Compute       11.6.0
Az.ResourceGraph 1.3.0
Az.Resources     10.0.0

2. Sign-in options are parameter sets (real metadata)

(Get-Command Connect-AzAccount).ParameterSets | ForEach-Object {
    '{0,-50} {1}' -f $_.Name, (($_.Parameters | Where-Object IsMandatory).Name -join ', ')
}
UserWithSubscriptionId
ServicePrincipalWithSubscriptionId                 Credential, ServicePrincipal, Tenant
UserWithCredential                                 Credential
ServicePrincipalCertificateWithSubscriptionId      CertificateThumbprint, ApplicationId, Tenant
ClientAssertionParameterSet                        ApplicationId, Tenant, FederatedToken
ServicePrincipalCertificateFileWithSubscriptionId  ApplicationId, Tenant, CertificatePath
AccessTokenWithSubscriptionId                      AccessToken, AccountId
ManagedServiceLogin                                Identity

3. Which cmdlets can preview (real metadata)

foreach ($n in 'Get-AzResourceGroup', 'New-AzResourceGroup', 'Remove-AzResourceGroup', 'Update-AzTag', 'Stop-AzVM', 'Set-AzContext') {
    $c = Get-Command $n
    $a = $c.ImplementingType.GetCustomAttributes([System.Management.Automation.CmdletAttribute], $true)[0]
    '{0,-24} WhatIf={1,-5} ConfirmImpact={2}' -f $n, $c.Parameters.ContainsKey('WhatIf'), $a.ConfirmImpact
}
Get-AzResourceGroup      WhatIf=False ConfirmImpact=None
New-AzResourceGroup      WhatIf=True  ConfirmImpact=Medium
Remove-AzResourceGroup   WhatIf=True  ConfirmImpact=Medium
Update-AzTag             WhatIf=True  ConfirmImpact=Medium
Stop-AzVM                WhatIf=True  ConfirmImpact=Medium
Set-AzContext            WhatIf=True  ConfirmImpact=Medium

ConfirmImpact Medium means no automatic prompt at the default $ConfirmPreference = 'High'. Remove-AzResourceGroup and Stop-AzVM ask their own “Are you sure?” question unless you pass -Force — so in -NonInteractive automation they need -Force, which is exactly why you run them with -WhatIf first.

4. A guarded session (sandbox)

Disable-AzContextAutosave -Scope Process | Out-Null
$sub = '00000000-0000-0000-0000-000000000000'          # your sandbox subscription ID
Connect-AzAccount -Tenant 'contoso.onmicrosoft.com' -Subscription $sub | Out-Null
Set-AzContext -Subscription $sub | Out-Null
$ctx = Get-AzContext
if ($ctx.Subscription.Id -ne $sub) { throw "Wrong subscription: $($ctx.Subscription.Name)" }
$ctx | Format-List Account, Tenant, Subscription, Environment
Account      : labadmin@contoso.onmicrosoft.com
Tenant       : 11111111-1111-1111-1111-111111111111
Subscription : 00000000-0000-0000-0000-000000000000
Environment  : AzureCloud

5. Read-only queries

Get-AzResourceGroup -Tag @{ owner = 'labadmin' } | Select-Object ResourceGroupName, Location, ProvisioningState
Get-AzVM -Status | Select-Object Name, ResourceGroupName, PowerState, @{ n = 'Size'; e = { $_.HardwareProfile.VmSize } }
ResourceGroupName Location      ProvisioningState
----------------- --------      -----------------
rg-pslab-h7       canadacentral Succeeded

Name   ResourceGroupName PowerState     Size
----   ----------------- ----------     ----
web-01 rg-shop-dev       VM running     Standard_B1s
web-02 rg-shop-prod      VM deallocated Standard_B2s

6. Preview a change

New-AzResourceGroup -Name rg-pslab-h7-tmp -Location canadacentral -Tag @{ owner = 'labadmin'; purpose = 'pslab' } -WhatIf
Remove-AzResourceGroup -Name rg-pslab-h7 -WhatIf
What if: Performing the operation "Create" on target "rg-pslab-h7-tmp".
What if: Performing the operation "Remove resource group" on target "rg-pslab-h7".

7. Az vs az: objects vs text (real)

Get-Command Get-AzVM -Syntax | Select-Object -First 1
$raw = az version --output json
$raw.GetType().Name; $raw.Count
($raw | ConvertFrom-Json).'azure-cli'
Get-AzVM [[-ResourceGroupName] <string>] [[-Name] <string>] [-Status] [-UserData] [-DefaultProfile <IAzureContextContainer>] [<CommonParameters>]
Object[]
6
2.84.0

How to verify: after every sign-in, print (Get-AzContext).Subscription.Id and compare it with the ID you expect — not the name, which is not unique. Common mistake: running Set-AzContext in one terminal while a long script runs in another with autosave on. Production use: start every runbook with Disable-AzContextAutosave -Scope Process, a sign-in method that fits the host (managed identity, OIDC), an explicit Set-AzContext, and a guard that throws on mismatch; give the identity Reader unless the job changes something.

Goal: Explore Az without touching a subscription, then (optionally) run a guarded read-only session. Environment: Az.Accounts + Az.Resources + Az.Compute installed (or saved to a folder). Cost: none; optional part is read-only.

Offline: count the Az.Resources cmdlets that support -WhatIf:
$all = Get-Command -Module Az.Resources -CommandType Cmdlet
'{0} cmdlets, {1} with -WhatIf' -f $all.Count, @($all | Where-Object { $_.Parameters.ContainsKey('WhatIf') }).Count

Your numbers depend on the Az.Resources version; compare Get- vs New-/Remove-/Set- verbs.

Offline: find how to filter resource groups by tag with help only: Get-Help Get-AzResourceGroup -Parameter Tag.
Optional (sandbox): write the guard as a function and use it at the top of every Azure script you write today:
function Assert-AzSubscription([Parameter(Mandatory)][string]$Id) {
    $ctx = Get-AzContext
    if (-not $ctx) { throw 'Not signed in: run Connect-AzAccount' }
    if ($ctx.Subscription.Id -ne $Id) { throw "Context is '$($ctx.Subscription.Name)' ($($ctx.Subscription.Id)), expected $Id" }
    Write-Verbose "Azure context OK: $($ctx.Subscription.Name)"
}
Optional (sandbox): read-only inventory:
Assert-AzSubscription -Id $sub -Verbose
Get-AzResourceGroup | Group-Object Location -NoElement | Sort-Object Count -Descending
Get-AzVM -Status | Group-Object PowerState -NoElement
Cleanup: Disconnect-AzAccount (signs out this process's context). Nothing was created.

Case 1: a cleanup job deleted groups in production

Problem: A nightly “delete expired lab groups” runbook removed resource groups in a production subscription. Root cause: the run-as identity had been granted access to a second subscription; Connect-AzAccount -Identity picked that one as the default, and the script never called Set-AzContext. The tag filter matched an old production group too. Fix: explicit Set-AzContext + guard; least-privilege RBAC scoped to the lab subscription; a -WhatIf dry-run report reviewed before enabling deletes; resource locks on production groups.

Case 2: a CI image that took 9 minutes to build

Problem: Each pipeline run installed Az (all 100+ modules) and imported it. Root cause: the roll-up module for a job that used three cmdlets. Fix: install Az.Accounts + the service modules used, with pinned versions, cached between runs; import explicitly with #Requires -Modules.

Case 3: “works on my machine” because of a saved context

Problem: A script worked for its author and failed for everyone else with “Run Connect-AzAccount to login”. Root cause: the author's saved context from yesterday; the script never signed in. Fix: scripts accept a context or sign in explicitly; test them with pwsh -NoProfile after Disconnect-AzAccount or with autosave disabled.

Common errors and fixes

Run Connect-AzAccount to login.

Cause: no context in this process (new runspace, autosave disabled, different user). Fix: sign in inside the script with a method that fits the host.

The subscription '…' could not be found / Set-AzContext fails

Cause: wrong tenant, or the identity has no role on that subscription. Fix: Get-AzSubscription -TenantId $t; check RBAC; pass -Tenant to Connect-AzAccount.

ManagedIdentityCredential authentication unavailable

Cause: -Identity outside Azure compute, or the identity is not enabled / not assigned. For user-assigned identities pass -AccountId <clientId>.

AADSTS700213 / AADSTS70021: No matching federated identity record found

Cause: the OIDC token's subject (repo, branch, environment) does not match the federated credential on the app registration. Fix: compare the sub claim with the credential's subject exactly (e.g. repo:org/repo:environment:prod).

Get-AzVM returns no PowerState

Cause: no -Status. Fix: Get-AzVM -Status, or Resource Graph's properties.extended.instanceView.powerState.code for large estates (Module 7).

Command-line exercises
1. Show the mandatory parameters of the parameter set that uses an OIDC token.
((Get-Command Connect-AzAccount).ParameterSets | Where-Object Name -eq 'ClientAssertionParameterSet').Parameters |
    Where-Object IsMandatory | Select-Object -ExpandProperty Name
2. List running VMs in a sandbox with name, group and size only.
Get-AzVM -Status | Where-Object PowerState -eq 'VM running' |
    Select-Object Name, ResourceGroupName, @{ n = 'Size'; e = { $_.HardwareProfile.VmSize } }
Scenario analysis
A developer wants to run a cleanup script from their laptop “just once” against a shared subscription. What do you require before it runs?

① Explicit context: Disable-AzContextAutosave -Scope Process, Set-AzContext by ID, and a guard. ② A dry run with -WhatIf that prints every target, reviewed by a second person. ③ Filters based on tags that mark ownership (owner, expires), not on name patterns. ④ Resource locks on anything critical. ⑤ Ideally, run it from a pipeline with a scoped identity instead of a personal account, so it is logged and repeatable.

Verified teaching videos

▶
Getting Started with Azure PowerShell — John Savill's Technical Training
English · installing Az, Connect-AzAccount, contexts (older Az versions; parameter names still apply)

Official documentation

Video storyboard (about 90 seconds)

These materials cannot generate video or MP3 directly; the storyboard and narration are provided for a video tool.

Shot 1 · 0–20s
Visual: six sign-in doors (browser, device code, managed identity, certificate, OIDC, secret) lead into one room called “Context”.
Narration: many ways in, one piece of state that decides everything after.
Shot 2 · 20–50s
Visual: two terminal windows share one context file; one window switches subscription, the other script's target flips.
Narration: contexts are saved and shared. Disable autosave in automation.
Shot 3 · 50–75s
Visual: a guard function throws in red when the subscription ID does not match.
Narration: assert the subscription by ID before any query or change.
Shot 4 · 75–90s
Visual: Get-AzVM objects vs az CLI JSON text, joined by ConvertFrom-Json.
Narration: Az gives objects; the CLI gives text you convert.
or score ≥ 70% on the Quiz

Module 5 · AWS.Tools: modular install, profiles, regions and queries

28:00 – 35:00 · AWS.Tools is one PowerShell module per AWS service, generated from the AWS SDK for .NET. Like Az, the hard parts are not the cmdlets but the invisible state: which credentials, which region, how many pages.
7 minMetadata: real (AWS.Tools 5.0.344)AWS calls: Expected output★★★★☆
Learning objectives
  • Install and update only the service modules you need with AWS.Tools.Installer, all on one version.
  • Predict which credentials a cmdlet uses (the documented V5 search order) and configure profiles and IAM Identity Center (SSO).
  • Control the region with -Region and Set-DefaultAWSRegion, and know where else it can come from.
  • Query EC2 and S3: unwrap Get-EC2Instance's Reservation → Instances shape, use -Filter, -Select, and know that V5 auto-iterates all pages (-NoAutoIteration to page manually).
Prerequisites: Modules 1–3. Optional AWS sandbox. Importance:★★★★☆

What: three ways AWS ships PowerShell

PackageWhat it isUse?
AWS.Tools.* (5.0.344 on the lab machine)One module per service (AWS.Tools.EC2: 843 commands, AWS.Tools.S3: 112 — verified), plus AWS.Tools.Common; cross-platform; auto-loading worksYes
AWS.Tools.Installer (2.0.6)Install-AWSToolsModule, Update-AWSToolsModule, Uninstall-AWSToolsModule: keeps all AWS.Tools modules on the same version and can clean up old ones (-Cleanup)Yes, to manage them
AWSPowerShell / AWSPowerShell.NetCoreLegacy single huge modules with every serviceNo, for new work

Why: V5 changed behavior you will notice

V5 change (AWS migration guide)Effect on scripts
Consistent auto-iteration: all paginated cmdlets fetch all pages by defaultLarge accounts → long calls and many API requests; use -NoAutoIteration + -NextToken to page yourself. Verified: Get-AWSAutoIterationMode reports standard
Nullable value typesUnset numbers/dates/booleans are $null, not 0 / 0001-01-01 / $false
Some empty collections are $nullUse @(…) and test with $null -eq (Module 7)
-PassThru removed; $AWSHistory removedUse -Select '^ParameterName' or -Select '*'
Credentials can come from AWS_PROFILE / AWS_ACCESS_KEY_ID … env vars; new error text “Failed to resolve AWS credentials”CI behaves like the AWS CLI
Ctrl+C cancels cmdletsInteractive comfort

How: credential search order (V5, documented)

  1. Literal keys on the command line (-AccessKey/-SecretKey) — avoid.
  2. -Credential (an AWSCredentials object, e.g. from Use-STSRole).
  3. A profile set for the session with Set-AWSCredential -ProfileName (or -ProfileName on the cmdlet). If it does not exist, the command throws — no silent fallback.
  4. AWS_ACCESS_KEY_ID + AWS_SECRET_ACCESS_KEY + AWS_SESSION_TOKEN (all three).
  5. The profile named by AWS_PROFILE.
  6. The default profile (SDK store, then shared credentials file, then AWS PS Default).
  7. EC2 instance profile (IAM role) credentials.

Region is resolved separately: -Region on the call → the shell default from Set-DefaultAWSRegion ($StoredAWSRegion) → AWS_REGION/AWS_DEFAULT_REGION → the profile's region → instance metadata. A wrong region is not an error: you just see an empty list.

When: SSO profiles for people, roles for machines

People: IAM Identity Center profiles created with aws configure sso (or Initialize-AWSSSOConfiguration), then Invoke-AWSSSOLogin / the CLI login refreshes short-lived credentials. Machines: instance profiles, ECS task roles, Lambda execution roles, or GitHub OIDC with aws-actions/configure-aws-credentials — no access keys on disk.

Common misconceptions① “Get-EC2Instance returns instances” — it returns Reservations; instances are in .Instances (verified OutputType: Amazon.EC2.Model.Reservation). ② “An empty result means no resources” — often the wrong region or account. ③ “Install-Module AWSPowerShell.NetCore is the modern way” — use AWS.Tools.*. ④ “Auto-iteration is free” — it makes as many API calls as there are pages, each counted against throttling limits. ⑤ “Set-AWSCredential -StoreAs is a safe vault” — it writes to the SDK store/credentials file; prefer SSO and roles.

Credential and region resolution

Get-EC2Instanceno -ProfileName Credentials: first match wins 1 -AccessKey/-SecretKey (avoid)2 -Credential object3 Set-AWSCredential -ProfileName (throws if missing)4 AWS_ACCESS_KEY_ID + SECRET + SESSION_TOKEN5 AWS_PROFILE6 default profile (SDK store / credentials file)7 EC2 instance profile rolenone → “Failed to resolve AWS credentials” Region-Region on the callSet-DefaultAWSRegion ($StoredAWSRegion)AWS_REGION / AWS_DEFAULT_REGIONprofile regionwrong region → empty result, no error Call + auto-iteration (V5)DescribeInstances page 1 … n→ Reservation objects-NoAutoIteration: one page + NextToken
Figure 7-8: credentials and region are resolved independently; both can be “right” for the wrong account or region

Credential and region resolution

Follow one Get-EC2Instance call through the credential chain, the region chain and pagination. Cloud outputs are Expected.

Ready.
Real mechanism behind the animation AWS.Tools.Common resolves an AWSCredentials object and a RegionEndpoint before each call using the documented chains, builds an SDK client (e.g. AmazonEC2Client), and calls the API. For paginated operations the cmdlet loops on NextToken unless -NoAutoIteration is set, writing each page's items to the pipeline. -Select chooses what to emit from each response (default Reservations for Get-EC2Instance).

Command table

CommandPurposeNotes
Install-AWSToolsModule EC2, S3, SecurityToken -CleanupInstall service modules (+ Common)Same version for all; -Cleanup removes older versions
Update-AWSToolsModule -CleanupUpdate all installed AWS.ToolsV5 by default; -MaximumVersion '4.9.999' to stay on V4
Set-AWSCredential -ProfileName dev-ssoSession default profileThrows if the profile does not exist
Invoke-AWSSSOLogin / Initialize-AWSSSOConfigurationIAM Identity CenterOr aws sso login --profile …
Set-DefaultAWSRegion -Region ca-central-1Session default regionGet-DefaultAWSRegion, $StoredAWSRegion
Get-AWSRegionRegion list (offline, from the SDK)45 regions in 5.0.344
Get-EC2Instance -Filter @{Name='tag:env';Values='prod'}Server-side filterReturns Reservations
Get-EC2Instance -Select 'Reservations.Instances'Unwrap in the cmdlet-Select '*' = whole response
Get-S3Bucket [-BucketRegion]List bucketsGlobal list; bucket regions differ
-NoAutoIteration -NextToken $t -MaxResult 100Manual pagingCheck -Select '*' for NextToken

1. Modules and versions (real; saved to a folder, see Module 0)

Get-Module -ListAvailable AWS.Tools.* | Sort-Object Name | Format-Table Name, Version
Import-Module AWS.Tools.EC2, AWS.Tools.S3
(Get-Command -Module AWS.Tools.EC2).Count
(Get-Command -Module AWS.Tools.S3).Count
Name                Version
----                -------
AWS.Tools.Common    5.0.344
AWS.Tools.EC2       5.0.344
AWS.Tools.Installer 2.0.6
AWS.Tools.S3        5.0.344

843
112

2. Region defaults are local state (real, no AWS call)

Get-AWSRegion | Where-Object Region -like 'ca-*'
Set-DefaultAWSRegion -Region ca-central-1
Get-DefaultAWSRegion
$StoredAWSRegion
Get-AWSAutoIterationMode
Region       Name                  IsShellDefault
------       ----                  --------------
ca-central-1 Canada (Central)      False
ca-west-1    Canada West (Calgary) False

Region       Name             IsShellDefault
------       ----             --------------
ca-central-1 Canada (Central) True

ca-central-1

AutoIterationMode
-----------------
standard

3. What Get-EC2Instance returns and accepts (real metadata)

(Get-Command Get-EC2Instance).OutputType.Name
(Get-Command Get-S3Bucket).OutputType.Name
$p = (Get-Command Get-EC2Instance).Parameters
'Select', 'NoAutoIteration', 'NextToken', 'MaxResult', 'Filter', 'Region', 'ProfileName' |
    ForEach-Object { '{0,-16} {1}' -f $_, $p[$_].ParameterType.Name }
(Get-Help Get-EC2Instance -Parameter Select).Description.Text
Amazon.EC2.Model.Reservation
Amazon.S3.Model.S3Bucket
Select           String
NoAutoIteration  SwitchParameter
NextToken        String
MaxResult        Nullable`1
Filter           Filter[]
Region           Object
ProfileName      String
Use the -Select parameter to control the cmdlet output. The default value is 'Reservations'. Specifying -Select '*' will result in the cmdlet returning the whole service response (Amazon.EC2.Model.DescribeInstancesResponse). Specifying the name of a property of type Amazon.EC2.Model.DescribeInstancesResponse will result in that property being returned. Specifying -Select '^ParameterName' will result in the cmdlet returning the selected cmdlet parameter value.

4. Sign in with an SSO profile and query (sandbox)

# once: aws configure sso   (creates profile 'pslab-sso' in ~/.aws/config)
aws sso login --profile pslab-sso
Set-AWSCredential -ProfileName pslab-sso
Set-DefaultAWSRegion -Region ca-central-1
(Get-STSCallerIdentity).Arn

$res = Get-EC2Instance -Filter @{ Name = 'tag:env'; Values = 'staging' }
$res.Count                   # reservations
$res.Instances.Count         # instances
$res.Instances | Select-Object InstanceId, InstanceType, PrivateIpAddress,
    @{ n = 'State'; e = { $_.State.Name.Value } },
    @{ n = 'Name';  e = { ($_.Tags | Where-Object Key -eq 'Name').Value } }
arn:aws:sts::111122223333:assumed-role/AWSReservedSSO_ReadOnly_0123abcd/labadmin
2
3

InstanceId InstanceType PrivateIpAddress State   Name
---------- ------------ ---------------- -----   ----
i-0aa1     t3.small     10.20.1.31       running web-01
i-0aa2     t3.small     10.20.1.32       running api-01
i-0bb3     r6i.large    10.20.1.33       stopped db-01

5. S3 and -Select

Get-S3Bucket | Select-Object BucketName, CreationDate | Sort-Object CreationDate
Get-EC2Instance -Select 'Reservations.Instances' | Measure-Object | Select-Object Count
Get-EC2Instance -NoAutoIteration -MaxResult 5 -Select '*' | Select-Object NextToken
BucketName                       CreationDate
----------                       ------------
pslab-logs-111122223333          2026-03-02 14:10:05
pslab-artifacts-111122223333     2026-09-18 08:41:27

Count
-----
    3

NextToken
---------

6. No credentials (what CI shows when the role is missing)

Get-EC2Instance -Region ca-central-1
Get-EC2Instance: Failed to resolve AWS credentials. The credential providers used to search for credentials returned the following errors:
…

How to verify: always print (Get-STSCallerIdentity).Arn and the region at the start of a run — the AWS equivalent of the Az context guard. Common mistake: (Get-EC2Instance).InstanceId returns nothing, because the reservations have no such property; use .Instances.InstanceId. Production use: pin AWS.Tools.* versions in CI, pass -Region explicitly in scripts that run in many regions (foreach ($r in $regions) { Get-EC2Instance -Region $r }), use roles or OIDC for machines, and keep auto-iteration in mind when estimating API calls.

Goal: Learn the AWS.Tools shapes offline, then (optionally) query a sandbox. Environment: AWS.Tools.EC2 + Common (installed or saved to a folder). Cost: none; Describe/List calls are free.

Offline: find EC2 cmdlets for the DescribeInstances family:
Get-Command -Module AWS.Tools.EC2 -Verb Get -Noun EC2Instance* | Select-Object -ExpandProperty Name
Offline: set and read the shell defaults as in block 2; then open a new pwsh and confirm $StoredAWSRegion is empty — the default is per session.
Offline: practice the Reservation → Instances shape on the sample file from Module 7 (~/pslab/tmp/ec2-describe.json has the same structure as Get-EC2Instance -Select '*').
Optional (sandbox): multi-region read-only sweep:
$regions = 'ca-central-1', 'us-east-1'
foreach ($r in $regions) {
    $n = @((Get-EC2Instance -Region $r).Instances).Count
    '{0,-14} {1} instances' -f $r, $n
}
Cleanup: Clear-DefaultAWSRegion; Clear-AWSCredential (session only). Nothing was created.

Case 1: the inventory that “lost” half the fleet

Problem: A compliance report listed 120 instances; the console showed 240. Root cause: the job ran with AWS_DEFAULT_REGION=us-east-1 on a runner, and half the fleet was in ca-central-1. No error — just an empty region. Fix: an explicit region list (or Get-EC2Region for enabled regions) and -Region on every call; the report prints the region and account it queried.

Case 2: a profile typo that fell back to admin keys

Problem: On an old V3-era jump host, a script with a misspelled profile ran with the default profile — which held long-lived admin keys. Root cause: a fallback chain plus a powerful default. Fix: no long-lived keys on hosts (SSO, roles); with Set-AWSCredential -ProfileName the current tools throw for a missing profile, so set it explicitly instead of relying on default; give the default profile nothing.

Case 3: throttled DescribeInstances during an incident

Problem: During an outage, ten engineers ran the same “list everything” script; EC2 API calls started returning RequestLimitExceeded, slowing the incident tooling. Root cause: auto-iteration over thousands of instances, repeated, without filters. Fix: server-side -Filter, cached inventories (Get-OpsCloudInventory output saved to JSON), and backoff on throttling errors.

Common errors and fixes

Failed to resolve AWS credentials …

Cause: nothing in the chain. Fix: aws sso login --profile p + -ProfileName p, or the role/OIDC step in CI. Check $env:AWS_PROFILE.

The SSO session associated with this profile has expired or is otherwise invalid

Fix: aws sso login --profile p (or Invoke-AWSSSOLogin); SSO credentials are short-lived by design.

No region specified or obtained from persisted/shell defaults
Set-DefaultAWSRegion -Region ca-central-1   # or -Region on each call
(Get-EC2Instance).InstanceId is empty
(Get-EC2Instance).Instances.InstanceId
Import-Module: Assembly with same name is already loaded (AWS.Tools.* version mix)

Cause: two AWS.Tools versions in one session. Fix: Update-AWSToolsModule -Cleanup; start a new session.

Command-line exercises
1. List every running instance's ID and Name tag in two regions in one table.
'ca-central-1','us-east-1' | ForEach-Object {
    $r = $_
    (Get-EC2Instance -Region $r -Filter @{ Name = 'instance-state-name'; Values = 'running' }).Instances |
        Select-Object @{ n='Region'; e={ $r } }, InstanceId, @{ n='Name'; e={ ($_.Tags | ? Key -eq 'Name').Value } }
}
2. Print which identity your session is using, without listing any resources (Get-STSCallerIdentity is in AWS.Tools.SecurityToken).
Get-STSCallerIdentity | Select-Object Account, Arn
Scenario analysis
A GitHub Actions job using AWS.Tools works on main but fails with credential errors on pull requests from forks. Why, and what is the right design?

With OIDC, the IAM role's trust policy restricts the token's sub claim (repository, branch, environment); fork PRs either get no id-token permission or a subject that does not match — correctly. Keep it: read-only checks for PRs can use a separate, narrowly scoped role trusted for pull_request, and anything with write access runs only on protected branches/environments. Never “fix” it by adding access keys as repository secrets.

Verified teaching videos

▶
AWS for Microsoft Workloads: Installing the AWS Tools for PowerShell — Amazon Web Services
English · official install walkthrough (check for V5 differences)
▶
Automating AWS with PowerShell: A Practical Guide — RTPSUG April 2026 — Research Triangle PowerShell Users Group
English · recent user-group session

Official documentation

Video storyboard (about 90 seconds)

These materials cannot generate video or MP3 directly; the storyboard and narration are provided for a video tool.

Shot 1 · 0–20s
Visual: a shelf of small modules (EC2, S3, IAM) replaces one giant box.
Narration: install only the services you use, all on one version.
Shot 2 · 20–50s
Visual: the seven-step credential ladder; a call climbs until it finds a match.
Narration: credentials resolve in a fixed order. Know which step you are on.
Shot 3 · 50–70s
Visual: a Reservation box opens to show Instance boxes.
Narration: Get-EC2Instance returns reservations. The instances are inside.
Shot 4 · 70–90s
Visual: a world map; one region lit, the rest empty, a report says “120”.
Narration: the wrong region is not an error, it is an empty answer.
or score ≥ 70% on the Quiz

Module 6 · Idempotent cloud changes: get-then-set, tags and ShouldProcess

35:00 – 42:00 · An automation run must be safe to repeat: the second run should change nothing. That means reading current state, comparing it with the desired state, changing only the difference, previewing it with -WhatIf, and treating “not found” differently from “something is broken”.
7 minMock API · real outputsAz/AWS: Expected output★★★★★
Learning objectives
  • Write get → compare → set functions that report Changed = $false on the second run.
  • Use tags as ownership and lifecycle metadata, and merge them instead of replacing them (Update-AzTag -Operation Merge, New-EC2Tag).
  • Wrap Az/AWS cmdlets in SupportsShouldProcess functions, and know the verified trap: a script's -WhatIf and -Verbose do not reach functions in a module unless you pass them.
  • Handle “not found” specifically (status 404, ResourceGroupNotFound, InvalidInstanceID.NotFound) and let every other error stop the run.
Prerequisites: Modules 1, 4, 5; Lesson 5 (ShouldProcess). Importance:★★★★★

What: idempotency in one sentence

Running the operation once or ten times leaves the system in the same state, and runs after the first report “no change”. Declarative tools (Bicep, Terraform) do this for you; PowerShell scripts must do it themselves.

PatternIdempotent?Why
New-AzResourceGroup -Name x every runPartly — Azure updates an existing group, but tags you pass replace the existing onesCreate-or-update semantics differ per API
POST /items every runNo — duplicates or 409POST creates
PUT /items/x with the full desired stateYes (by HTTP definition)PUT replaces with the same content
GET → compare → PUT/PATCH only the differenceYes, and it can report and previewThe pattern of this module

Why: tags are how automation knows what it owns

Tag everything you create: owner, managedBy=opskit, env, expires, costCenter. Cleanup and sync jobs then act only on resources with managedBy=opskit, never on name patterns. Merge tags (Update-AzTag -Operation Merge; New-EC2Tag adds/overwrites only the keys given) so other teams' tags survive.

How: “not found” is data, other errors are failures

SourceNot found looks like (verified for the mock; Expected for clouds)Handle
REST / mock APIHttpResponseException, StatusCode = NotFoundcatch [Microsoft.PowerShell.Commands.HttpResponseException] + status check; rethrow others
AzGet-AzResourceGroup -Name x: “Provided resource group does not exist.”-ErrorAction SilentlyContinue -ErrorVariable e, then inspect $e; or query with Get-AzResourceGroup | Where-Object / Resource Graph (empty = not found)
AWSAmazonEC2Exception with ErrorCode = InvalidInstanceID.NotFoundcatch [Amazon.EC2.AmazonEC2Exception] { if ($_.Exception.ErrorCode -like '*.NotFound') … else { throw } }

When: the preference-propagation trap (verified)

A script run with -WhatIf -Verbose sets $WhatIfPreference and $VerbosePreference in the script's scope. Functions defined in the script see them. Functions exported from a module do not — they resolve variables in the module's scope and then the global scope. Verified on 7.6.10: the module function performed the change while the script was running with -WhatIf. Fixes: do ShouldProcess in the script and call the module function with -Confirm:$false, or pass the switches on: -WhatIf:$WhatIfPreference -Verbose:($VerbosePreference -eq 'Continue'). The integrated lab's Sync-OpsInventory.ps1 does both.

Common misconceptions① “-ErrorAction SilentlyContinue on the GET is how you test existence” — it also hides 401s, throttling and typos (Module 1, Case 2). ② “-WhatIf on my script makes everything inside safe” — not module functions, and not native tools (az, aws). ③ “Tags passed to New-… are merged” — New-AzResourceGroup -Tag on an existing group replaces the tag set. ④ “Idempotent means no errors on the second run” — it means no changes; a create that fails with 409 on run two is not idempotent, it is lucky. ⑤ “Compare with -eq is enough” — tag values are case-sensitive strings for some providers; compare with -ceq and normalize types.

Get → compare → set

GET currentread-only Status?404 → warn / createother error → throw Comparedesired vs current no diff Changed = $falsereturn, nothing sent diff ShouldProcess-WhatIf → report PUT / UpdateChanged = $true Script -WhatIf → module function: preference NOT inheritedpass -WhatIf:$WhatIfPreference, or ShouldProcess in the caller + -Confirm:$false
Figure 7-9: only the “diff” path sends a write, and only after ShouldProcess approves it

Where preference variables are visible

Global scope ($WhatIfPreference = False) Script scope: caller.ps1 -WhatIf -Verbose$WhatIfPreference = TrueSet-Local (function in the script): sees True ✓child scopes inherit Module scope: PrefDemo.psm1Set-Demo looks up: module → globalsees False → CHANGED ✗unless -WhatIf is passed explicitly
Figure 7-10: module functions have their own scope chain; the caller's script scope is not on it

Get-then-set decision path

Runs of Set-LabServerTag against the mock API (real) and of the same pattern around Az (Expected).

Ready.
Real mechanism behind the animation $PSCmdlet.ShouldProcess() checks the caller's -WhatIf/-Confirm and the $WhatIfPreference/$ConfirmPreference visible in the function's own scope chain. For a function in a script, that chain includes the script scope; for a function in a module, it is module scope → global scope. Typed catch [HttpResponseException] blocks match on the exception type, so other failures (refused connection: HttpRequestException) fall through to the caller.

Command table

CommandPurposeNotes
[CmdletBinding(SupportsShouldProcess)] + $PSCmdlet.ShouldProcess($target, $action)Preview / confirm writesPut the GET and compare outside, the write inside
catch [Microsoft.PowerShell.Commands.HttpResponseException]HTTP status errors onlyThen check .Response.StatusCode
Update-AzTag -ResourceId $id -Tag $t -Operation MergeMerge tags in AzureReplace / Delete also exist
Get-AzResourceGroup -Name $n -ErrorAction SilentlyContinue -ErrorVariable eExistence check with evidenceInspect $e, don't ignore it
New-EC2Tag -Resource $id -Tag @{Key='owner';Value='x'}Add/overwrite AWS tagsOther keys stay
-WhatIf:$WhatIfPreference -Verbose:($VerbosePreference -eq 'Continue')Pass preferences into module functionsOr a splat @vb

Set-LabServerTag: get → compare → set against the mock API

Save as ~/pslab/scripts/Set-LabServerTag.ps1 and dot-source it.

function Set-LabServerTag {
    <#
    .SYNOPSIS
        Idempotently merges tags into a server of the mock API (get -> compare -> set).
    #>
    [CmdletBinding(SupportsShouldProcess)]
    param(
        [Parameter(Mandatory)] [string]$Env,
        [Parameter(Mandatory)] [string]$Name,
        [Parameter(Mandatory)] [hashtable]$Tag,
        [string]$BaseUri = 'http://127.0.0.1:5050'
    )
    $uri = "$BaseUri/api/servers/$Env/$Name/tags"

    # 1. GET the current state; "not found" is a normal answer, anything else is a real error
    try {
        $current = (Invoke-RestMethod $uri).tags
    }
    catch [Microsoft.PowerShell.Commands.HttpResponseException] {
        if ($_.Exception.Response.StatusCode -eq [System.Net.HttpStatusCode]::NotFound) {
            Write-Warning "Server $Env/$Name does not exist; nothing to tag."
            return
        }
        throw
    }

    # 2. COMPARE: build the desired state from the current one
    $desired = @{}
    foreach ($p in $current.PSObject.Properties) { $desired[$p.Name] = $p.Value }
    $changes = foreach ($k in $Tag.Keys) {
        if ("$($desired[$k])" -cne "$($Tag[$k])") { "$k=$($Tag[$k])"; $desired[$k] = $Tag[$k] }
    }

    # 3. SET only when something differs, and only through ShouldProcess
    if (-not $changes) {
        Write-Verbose "$Env/$Name already has the desired tags"
        return [pscustomobject]@{ Server = "$Env/$Name"; Changed = $false; Changes = '' }
    }
    if ($PSCmdlet.ShouldProcess("$Env/$Name", "Set tags $($changes -join ', ')")) {
        $null = Invoke-RestMethod $uri -Method Put -Body ($desired | ConvertTo-Json) -ContentType 'application/json'
        [pscustomobject]@{ Server = "$Env/$Name"; Changed = $true; Changes = $changes -join ', ' }
    }
}
. ~/pslab/scripts/Set-LabServerTag.ps1
$tags = @{ owner = 'team-web'; managedBy = 'opskit' }
Set-LabServerTag -Env prod -Name web-01 -Tag $tags -WhatIf
Set-LabServerTag -Env prod -Name web-01 -Tag $tags
Set-LabServerTag -Env prod -Name web-01 -Tag $tags -Verbose
What if: Performing the operation "Set tags managedBy=opskit, owner=team-web" on target "prod/web-01".

Server      Changed Changes
------      ------- -------
prod/web-01    True managedBy=opskit, owner=team-web

VERBOSE: WebRequest: v1.1 GET http://127.0.0.1:5050/api/servers/prod/web-01/tags
VERBOSE: WebResponse: 200 OK with application/json payload with body size 73 B (73 bytes)
VERBOSE: prod/web-01 already has the desired tags

Server      Changed Changes
------      ------- -------
prod/web-01   False
Set-LabServerTag -Env prod -Name web-01 -Tag @{ owner = 'team-platform' }
(Invoke-RestMethod http://127.0.0.1:5050/api/servers/prod/web-01/tags).tags
Set-LabServerTag -Env prod -Name web-99 -Tag $tags
try { Set-LabServerTag -Env prod -Name web-01 -Tag $tags -BaseUri http://127.0.0.1:5999 }
catch { 'real error, not swallowed: ' + $_.Exception.Message }
Server      Changed Changes
------      ------- -------
prod/web-01    True owner=team-platform

managedBy owner
--------- -----
opskit    team-platform

WARNING: Server prod/web-99 does not exist; nothing to tag.
real error, not swallowed: No connection could be made because the target machine actively refused it. (127.0.0.1:5999)

The merge kept managedBy while changing owner; the missing server is a warning; the refused connection (an HttpRequestException, not an HttpResponseException) went straight past the typed catch to the caller.

The preference trap, reproduced

# ~/pslab/tmp/PrefDemo/PrefDemo.psm1
function Set-Demo {
    [CmdletBinding(SupportsShouldProcess)]
    param([string]$Name)
    Write-Verbose "Set-Demo: verbose is visible"
    if ($PSCmdlet.ShouldProcess($Name, 'Change')) { "Set-Demo: CHANGED $Name" }
}

# ~/pslab/tmp/caller.ps1
[CmdletBinding(SupportsShouldProcess)]
param()
Import-Module (Join-Path $PSScriptRoot 'PrefDemo') -Force -Verbose:$false
function Set-Local { [CmdletBinding(SupportsShouldProcess)] param([string]$Name)
    Write-Verbose "Set-Local: verbose is visible"
    if ($PSCmdlet.ShouldProcess($Name, 'Change')) { "Set-Local: CHANGED $Name" } }
"WhatIfPreference in script = $WhatIfPreference; VerbosePreference = $VerbosePreference"
Set-Local -Name a
Set-Demo -Name b
Set-Demo -Name c -WhatIf:$WhatIfPreference -Verbose:($VerbosePreference -eq 'Continue')
& ~/pslab/tmp/caller.ps1 -WhatIf -Verbose
WhatIfPreference in script = True; VerbosePreference = Continue
VERBOSE: Set-Local: verbose is visible
What if: Performing the operation "Change" on target "a".
Set-Demo: CHANGED b
VERBOSE: Set-Demo: verbose is visible
What if: Performing the operation "Change" on target "c".

The same pattern around Az (sandbox)

function Set-OpsAzOwnerTag {
    [CmdletBinding(SupportsShouldProcess)]
    param([Parameter(Mandatory)][string]$ResourceGroupName, [Parameter(Mandatory)][string]$Owner)
    $rg = Get-AzResourceGroup -Name $ResourceGroupName -ErrorAction SilentlyContinue -ErrorVariable e
    if (-not $rg) {
        if ($e -and "$($e[0])" -notmatch 'does not exist') { throw $e[0] }    # auth, throttling, typos …
        Write-Warning "Resource group $ResourceGroupName not found"; return
    }
    if ($rg.Tags -and $rg.Tags['owner'] -ceq $Owner -and $rg.Tags['managedBy'] -ceq 'opskit') {
        Write-Verbose 'Tags already correct'; return
    }
    if ($PSCmdlet.ShouldProcess($ResourceGroupName, "Merge tags owner=$Owner, managedBy=opskit")) {
        Update-AzTag -ResourceId $rg.ResourceId -Tag @{ owner = $Owner; managedBy = 'opskit' } -Operation Merge -Confirm:$false
    }
}
Set-OpsAzOwnerTag -ResourceGroupName rg-pslab-h7 -Owner labadmin -WhatIf
Set-OpsAzOwnerTag -ResourceGroupName rg-pslab-h7 -Owner labadmin
Set-OpsAzOwnerTag -ResourceGroupName rg-pslab-h7 -Owner labadmin -Verbose
Set-OpsAzOwnerTag -ResourceGroupName rg-does-not-exist -Owner labadmin
What if: Performing the operation "Merge tags owner=labadmin, managedBy=opskit" on target "rg-pslab-h7".

Id         : /subscriptions/00000000-0000-0000-0000-000000000000/resourceGroups/rg-pslab-h7/providers/Microsoft.Resources/tags/default
Name       : default
Type       : Microsoft.Resources/tags
Properties :
             Name       Value
             =========  ========
             owner      labadmin
             managedBy  opskit
             purpose    pslab

VERBOSE: Tags already correct
WARNING: Resource group rg-does-not-exist not found

How to verify: run every change function three times — -WhatIf, real, real again — and require the third run to report no change. Common mistake: using -ErrorAction SilentlyContinue without -ErrorVariable: an expired token then looks like “not found”, and the function tries to create. Production use: scheduled sync jobs run nightly with -WhatIf into a report (drift detection), and in “apply” mode only after review; they act only on resources tagged managedBy=opskit.

Goal: Make a change function idempotent and prove it. Environment: mock API running. Cost: none.

Run Set-LabServerTag three times (WhatIf, apply, apply) for staging/api-01 with @{ owner = 'team-api'; expires = '2026-12-31' }. The third run must show Changed = False.
Prove that other tags survive: set @{ costCenter = 'cc-200' } and read the tags; owner and expires must still be there.
(Invoke-RestMethod http://127.0.0.1:5050/api/servers/staging/api-01/tags).tags
costCenter owner    expires
---------- -----    -------
cc-200     team-api 2026-12-31
Reproduce the preference trap: create the two files from the Commands tab in ~/pslab/tmp, run & ~/pslab/tmp/caller.ps1 -WhatIf, and find the line that should not be there.
Fix it two ways: ① pass -WhatIf:$WhatIfPreference; ② wrap the call in the script's own if ($PSCmdlet.ShouldProcess(…)) and call the module function with -Confirm:$false. Re-run with -WhatIf: no “CHANGED” line.
Cleanup: Remove-Item ~/pslab/tmp/PrefDemo, ~/pslab/tmp/caller.ps1 -Recurse. Tags live only in the mock's memory and disappear when it stops.

Case 1: a “dry run” that changed production

Problem: A change ticket required ./Rotate-Keys.ps1 -WhatIf output as evidence. The dry run rotated the keys. Root cause: the script called Reset-OpsKey from a company module; the script's $WhatIfPreference never reached the module function. Fix: ShouldProcess in the script around each call + -Confirm:$false on the inner call; a Pester test (Lesson 8) that runs the script with -WhatIf against mocks and asserts zero write calls.

Case 2: tags wiped by a redeploy

Problem: Finance tags on resource groups disappeared every Monday. Root cause: a weekly script ran New-AzResourceGroup -Name … -Tag @{ env = 'prod' } -Force, replacing the whole tag set. Fix: create only if missing; maintain tags with Update-AzTag -Operation Merge; enforce required tags with Azure Policy instead of scripts.

Case 3: a cleanup that deleted the wrong VMs

Problem: “Delete VMs named tmp-* older than 7 days” deleted a vendor's tmp-sql01. Root cause: ownership inferred from names. Fix: act only on managedBy=opskit and expires tags written by the creating automation; report first, delete after a grace period.

Common errors and fixes

My script's -WhatIf still changed something

Cause: a module function or a native tool did the write. Fix: pass -WhatIf:$WhatIfPreference or ShouldProcess in the caller; native tools need their own dry-run flag.

The second run creates duplicates or fails with 409 Conflict

Cause: create without checking. Fix: GET first (or PUT with a deterministic ID); treat 409 as “already exists” only if the existing object matches.

catch [HttpResponseException] never runs

Cause: the failure is an HttpRequestException (network) or TaskCanceledException (timeout). That is usually what you want: those are not “not found”.

Update-AzTag: The client '…' does not have authorization to perform action 'Microsoft.Resources/tags/write'

Cause: Reader role. Fix: Tag Contributor at the right scope — a narrower role than Contributor for tag-only automation.

Tag comparison always says “changed”

Cause: comparing a Hashtable with a PSCustomObject or different value types/case. Fix: normalize to strings and compare key by key (-ceq), as Set-LabServerTag does.

Command-line exercises
1. Write a typed catch that returns $null for 404 and rethrows anything else.
try { Invoke-RestMethod $uri }
catch [Microsoft.PowerShell.Commands.HttpResponseException] {
    if ($_.Exception.Response.StatusCode -eq 'NotFound') { $null } else { throw }
}
2. In a script with SupportsShouldProcess, call a module function so that the script's -WhatIf and -Verbose apply.
$common = @{ WhatIf = $WhatIfPreference; Verbose = $VerbosePreference -eq 'Continue' }
Set-OpsThing -Name x @common
Scenario analysis
A nightly job ensures every resource group has an owner tag by copying it from a CMDB. Some nights it reports 300 changes, other nights 0, although nobody edits tags. Investigate.

Likely non-idempotent comparison: e.g. CMDB returns "Team-Web" and Azure stores "team-web" and the code uses -ceq on one side only, or the CMDB API pages and some nights returns fewer rows (no pagination loop, Module 2) so the job “fixes” tags to empty/default values. Check: log desired vs current for one flapping group; verify the CMDB row count against its total; normalize case consistently; and never write when the desired value is missing — treat missing input as an error, not as “remove tag”.

Verified teaching videos

▶
PowerShell Master Class - Automation — John Savill's Technical Training
English · automation design, Azure Automation and runbooks
▶
How to use PowerShell Try, Catch and the Write-Verbose and Write-Debug — John Savill's Technical Training
English · error handling and verbose output used in get-then-set functions

No verified video was found that demonstrates preference propagation into module functions; rely on this module's reproduction.

Official documentation

Video storyboard (about 90 seconds)

These materials cannot generate video or MP3 directly; the storyboard and narration are provided for a video tool.

Shot 1 · 0–25s
Visual: the same script runs three times; a counter shows “2 changes, 0, 0”.
Narration: idempotent means the second run changes nothing.
Shot 2 · 25–50s
Visual: GET, compare, ShouldProcess, PUT as four gates; only a diff opens the last two.
Narration: read, compare, preview, then write only the difference.
Shot 3 · 50–75s
Visual: a WhatIf umbrella over a script; a module function stands outside it, getting wet.
Narration: preferences do not cross into modules. Pass them on.
Shot 4 · 75–90s
Visual: a 404 goes into a “not found” tray, a 401 sets off an alarm.
Narration: not found is data; everything else stops the run.
or score ≥ 70% on the Quiz

Module 7 · Cloud data processing: shaping JSON, Resource Graph and reports

42:00 – 50:00 · Cloud APIs answer with deep, nested JSON. Reports need flat rows. This module turns EC2 and Resource Graph shapes into tables with -ExpandProperty, member enumeration and calculated properties, queries Azure at scale with KQL, and exports CSV/JSON that survive a round trip.
8 minSample JSON · real outputsSearch-AzGraph: Expected output★★★★☆
Learning objectives
  • Flatten nested arrays with member enumeration and Select-Object -ExpandProperty, and nested objects with calculated properties.
  • Turn tag arrays ([{Key,Value}], AWS) and tag objects ({env: …}, Azure) into columns.
  • Query Azure Resource Graph with Search-AzGraph: KQL project/where/summarize, -First up to 1,000 and -SkipToken paging.
  • Export reports: Export-Csv only after flattening, ConvertTo-Json -Depth, and know the empty-collection count trap.
Prerequisites: Lesson 1 Module 6 (Select/Group/Measure), Lesson 2 (JSON). Importance:★★★★☆

What: three shapes you will meet

ShapeExampleFlatten with
Envelope + list{ value: [...], nextLink }, { data: [...], skipToken }, { Reservations: [...] }.value / .data (after paging)
List inside listReservations → Instances (AWS); VM → NICs → IP configs (Azure)Member enumeration $r.Reservations.Instances or Select-Object -ExpandProperty Instances
Object inside objectproperties.hardwareProfile.vmSize, State.NameCalculated property @{ n = 'size'; e = { $_.properties.hardwareProfile.vmSize } }
Tags as key/value listAWS Tags: [{Key:'Name',Value:'web-01'}]($_.Tags | Where-Object Key -eq 'Name').Value
Tags as objectAzure tags: { env: 'prod' }$_.tags.env; missing tag → $null (?? '(none)')

Why: CSV cannot hold nesting

Export-Csv calls ToString() on every property: a nested object becomes @{env=prod; owner=team-web}, a deeper one @{hardwareProfile=; extended=} (verified below). Always select flat properties first, then export. For JSON, pass -Depth on the way out — ConvertTo-Json truncates at 2 levels and only warns.

How: Resource Graph instead of N×M API calls

Listing VMs with their power state across 50 subscriptions via Get-AzVM -Status means hundreds of ARM calls and switching contexts. Azure Resource Graph indexes resource properties for every subscription you can read and answers a KQL query in one call (verified: Search-AzGraph -First accepts 1–1000; the response is a list with Data and SkipToken). It is read-only, free, and fast — but slightly delayed (seconds to minutes after changes) and limited to what Resource Graph indexes.

Resources
| where type =~ 'microsoft.compute/virtualmachines'
| extend env = tostring(tags.env), power = tostring(properties.extended.instanceView.powerState.code)
| project name, resourceGroup, location, env, size = tostring(properties.hardwareProfile.vmSize), power
| order by name asc

When: cost-safe reporting

  • Prefer list/query APIs (Resource Graph, Describe*, List*) — they are free and read-only.
  • Filter on the server (-Filter for EC2, KQL where) instead of downloading everything and filtering in PowerShell — fewer pages, fewer throttles.
  • Cache: write the shaped inventory to JSON once, report from the file many times.
  • Cost data itself (Cost Management, Cost Explorer) is billed per request on AWS — do not poll it in a loop.
Common misconceptions① “@($x.Items).Count is always safe” — if $x.Items is an empty array, member enumeration on an empty list returns $null and @($null).Count is 1 (verified below). ② “Export-Csv handles objects” — only flat ones. ③ “Resource Graph is real-time” — it is eventually consistent. ④ “KQL == is case-insensitive” — == is case-sensitive, =~ is not; resource types are lower-case in some places and mixed in others. ⑤ “-ExpandProperty keeps the parent's properties” — it outputs the child objects (with parent properties added only if you also select them, which can collide).

From raw JSON to a report

Raw JSONAPI / filenested 4–6 levels ConvertFrom-JsonPSCustomObject tree-AsHashtable option Unwrap lists.Reservations.Instances-ExpandProperty Calculated props@{n='power';e={…}}tags → columns Flat rowsWhere / Group / Sort→ CSV, JSON, HTML Export-Csv before flattening"@{env=prod; owner=team-web}""@{hardwareProfile=; extended=}" ConvertTo-Json without -Depth"instanceView": "@{powerState=}"+ WARNING on a stream nobody reads
Figure 7-11: flatten in the middle of the pipeline; export only flat rows — both red boxes are reproduced in the Commands tab

Resource Graph vs per-subscription calls

Get-AzVM -Status per subscriptionforeach sub: Set-AzContext → list VMs→ instance view per VMhundreds of ARM calls, throttlingminutes Search-AzGraph (KQL)one query across all readable subscriptions≤ 1,000 rows per page + SkipTokenread-only, free, indexedseconds (eventually consistent)
Figure 7-12: for inventory and compliance reports, query the index; for the exact live state of one resource, call its API

From raw JSON to a report

Step through each shaping pipeline; red marks a step that loses data.

Ready.
Real mechanism behind the animation Member enumeration ($list.Property) runs a loop for you and collects each element's property; nested arrays are flattened one level. On an empty collection it yields nothing, which in an expression context becomes $null. Export-Csv writes one column per property of the first object and calls ToString() on each value; PSCustomObject.ToString() produces the @{…} text you see.

Command table

CommandPurposeNotes
Get-Content f -Raw | ConvertFrom-Json [-AsHashtable] [-Depth n]Parse-AsHashtable → OrderedHashtable on 7.6 (verified)
$x.Reservations.InstancesFlatten via member enumerationEmpty-list trap: use .Count without @() or ForEach-Object
Select-Object -ExpandProperty InstancesFlatten in a pipelineStreams child objects
Select-Object @{ n = 'x'; e = { $_.a.b.c } }Calculated columnUse ?? for defaults
.Where({ … }), .ForEach({ … })Fast in-memory filterWorks on nested collections
Search-AzGraph -Query $kql -First 1000 [-SkipToken $t] [-Subscription …] [-ManagementGroup …] [-UseTenantScope]Resource GraphResponse: list + .SkipToken, .Data
Export-Csv -NoTypeInformationFlat report7.x omits the type line by default
ConvertTo-Json -Depth 10 | Set-ContentStructured reportRound-trip test with ConvertFrom-Json

Create the two sample files

Same structure as Get-EC2Instance -Select '*' / aws ec2 describe-instances and as a Resource Graph response. Values are invented.

Set-Location ~/pslab
@'
{"Reservations":[
 {"ReservationId":"r-0a1","OwnerId":"111122223333","Instances":[
   {"InstanceId":"i-0aa1","InstanceType":"t3.small","PrivateIpAddress":"10.20.1.31","State":{"Code":16,"Name":"running"},
    "Placement":{"AvailabilityZone":"ca-central-1a"},"Tags":[{"Key":"Name","Value":"web-01"},{"Key":"env","Value":"staging"}]},
   {"InstanceId":"i-0aa2","InstanceType":"t3.small","PrivateIpAddress":"10.20.1.32","State":{"Code":16,"Name":"running"},
    "Placement":{"AvailabilityZone":"ca-central-1b"},"Tags":[{"Key":"Name","Value":"api-01"},{"Key":"env","Value":"staging"}]}]},
 {"ReservationId":"r-0b2","OwnerId":"111122223333","Instances":[
   {"InstanceId":"i-0bb3","InstanceType":"r6i.large","PrivateIpAddress":"10.20.1.33","State":{"Code":80,"Name":"stopped"},
    "Placement":{"AvailabilityZone":"ca-central-1a"},"Tags":[{"Key":"Name","Value":"db-01"},{"Key":"env","Value":"staging"}]}]}
]}
'@ | Set-Content ./tmp/ec2-describe.json
@'
{"totalRecords":4,"count":4,"data":[
 {"name":"web-01","resourceGroup":"rg-shop-prod","location":"canadacentral","tags":{"env":"prod","owner":"team-web"},
  "properties":{"hardwareProfile":{"vmSize":"Standard_B2s"},"extended":{"instanceView":{"powerState":{"code":"PowerState/running"}}}}},
 {"name":"web-02","resourceGroup":"rg-shop-prod","location":"canadacentral","tags":{"env":"prod"},
  "properties":{"hardwareProfile":{"vmSize":"Standard_B2s"},"extended":{"instanceView":{"powerState":{"code":"PowerState/deallocated"}}}}},
 {"name":"api-01","resourceGroup":"rg-shop-prod","location":"canadacentral","tags":{"env":"prod","owner":"team-api"},
  "properties":{"hardwareProfile":{"vmSize":"Standard_D2s_v5"},"extended":{"instanceView":{"powerState":{"code":"PowerState/running"}}}}},
 {"name":"web-01","resourceGroup":"rg-shop-dev","location":"canadacentral","tags":{"env":"dev"},
  "properties":{"hardwareProfile":{"vmSize":"Standard_B1s"},"extended":{"instanceView":{"powerState":{"code":"PowerState/running"}}}}}
],"skipToken":null}
'@ | Set-Content ./tmp/arg-vms.json
Get-ChildItem ./tmp/ec2-describe.json, ./tmp/arg-vms.json | Format-Table Name, Length
Name              Length
----              ------
ec2-describe.json    905
arg-vms.json        1040

EC2: Reservations → Instances → rows

$ec2 = Get-Content ./tmp/ec2-describe.json -Raw | ConvertFrom-Json
$ec2.Reservations.Count
$ec2.Reservations.Instances.Count
$ec2.Reservations | Select-Object -ExpandProperty Instances | Select-Object InstanceId, InstanceType
2
3

InstanceId InstanceType
---------- ------------
i-0aa1     t3.small
i-0aa2     t3.small
i-0bb3     r6i.large
$ec2.Reservations.Instances | Select-Object InstanceId,
    @{ n = 'Name';  e = { ($_.Tags | Where-Object Key -eq 'Name').Value } },
    @{ n = 'Env';   e = { ($_.Tags | Where-Object Key -eq 'env').Value } },
    @{ n = 'State'; e = { $_.State.Name } },
    @{ n = 'AZ';    e = { $_.Placement.AvailabilityZone } },
    PrivateIpAddress | Format-Table
$ec2.Reservations.Instances.Where({ $_.State.Name -eq 'stopped' }).InstanceId
InstanceId Name   Env     State   AZ            PrivateIpAddress
---------- ----   ---     -----   --            ----------------
i-0aa1     web-01 staging running ca-central-1a 10.20.1.31
i-0aa2     api-01 staging running ca-central-1b 10.20.1.32
i-0bb3     db-01  staging stopped ca-central-1a 10.20.1.33

i-0bb3

With real Get-EC2Instance objects, State.Name is an InstanceStateName class: use $_.State.Name.Value for the string.

Resource Graph: nested properties and tags → report

$arg = Get-Content ./tmp/arg-vms.json -Raw | ConvertFrom-Json
$vms = $arg.data | Select-Object name, resourceGroup,
    @{ n = 'env';   e = { $_.tags.env } },
    @{ n = 'owner'; e = { $_.tags.owner ?? '(none)' } },
    @{ n = 'size';  e = { $_.properties.hardwareProfile.vmSize } },
    @{ n = 'power'; e = { $_.properties.extended.instanceView.powerState.code -replace '^PowerState/' } }
$vms | Format-Table
$vms | Group-Object power -NoElement
$vms | Where-Object owner -eq '(none)' | ForEach-Object { "$($_.resourceGroup)/$($_.name)" }
name   resourceGroup env  owner    size            power
----   ------------- ---  -----    ----            -----
web-01 rg-shop-prod  prod team-web Standard_B2s    running
web-02 rg-shop-prod  prod (none)   Standard_B2s    deallocated
api-01 rg-shop-prod  prod team-api Standard_D2s_v5 running
web-01 rg-shop-dev   dev  (none)   Standard_B1s    running

Count Name
----- ----
    1 deallocated
    3 running

rg-shop-prod/web-02
rg-shop-dev/web-01

Export: flat CSV works, nested CSV does not

$vms | Export-Csv ./tmp/vm-report.csv -NoTypeInformation
Get-Content ./tmp/vm-report.csv
$arg.data[0] | Export-Csv ./tmp/bad.csv -NoTypeInformation
Get-Content ./tmp/bad.csv
"name","resourceGroup","env","owner","size","power"
"web-01","rg-shop-prod","prod","team-web","Standard_B2s","running"
"web-02","rg-shop-prod","prod","(none)","Standard_B2s","deallocated"
"api-01","rg-shop-prod","prod","team-api","Standard_D2s_v5","running"
"web-01","rg-shop-dev","dev","(none)","Standard_B1s","running"
"name","resourceGroup","location","tags","properties"
"web-01","rg-shop-prod","canadacentral","@{env=prod; owner=team-web}","@{hardwareProfile=; extended=}"

JSON depth, hashtables, and the empty-collection trap

$arg.data[0] | ConvertTo-Json -Compress
$arg.data[0] | ConvertTo-Json -Depth 10 -Compress
$h = Get-Content ./tmp/arg-vms.json -Raw | ConvertFrom-Json -AsHashtable
$h.GetType().Name; $h['data'][0]['tags']['env']

$none = '{"Reservations":[]}' | ConvertFrom-Json
"a=" + @($none.Reservations.Instances).Count
"b=" + $none.Reservations.Instances.Count
"c=" + @($none.Reservations | ForEach-Object Instances).Count
WARNING: Resulting JSON is truncated as serialization has exceeded the set depth of 2.
{"name":"web-01","resourceGroup":"rg-shop-prod","location":"canadacentral","tags":{"env":"prod","owner":"team-web"},"properties":{"hardwareProfile":{"vmSize":"Standard_B2s"},"extended":{"instanceView":"@{powerState=}"}}}
{"name":"web-01","resourceGroup":"rg-shop-prod","location":"canadacentral","tags":{"env":"prod","owner":"team-web"},"properties":{"hardwareProfile":{"vmSize":"Standard_B2s"},"extended":{"instanceView":{"powerState":{"code":"PowerState/running"}}}}}
OrderedHashtable
prod
a=1
b=0
c=0

Search-AzGraph (sandbox)

Import-Module Az.ResourceGraph
(Get-Command Search-AzGraph).OutputType.Type.Name           # real: no sign-in needed
$kql = @'
Resources
| where type =~ 'microsoft.compute/virtualmachines'
| extend env = tostring(tags.env), owner = tostring(tags.owner),
         power = tostring(properties.extended.instanceView.powerState.code)
| project name, resourceGroup, env, owner, power
'@
$rows = [System.Collections.Generic.List[object]]::new()
$page = Search-AzGraph -Query $kql -First 1000
while ($page) {
    $rows.AddRange(@($page))
    $page = if ($page.SkipToken) { Search-AzGraph -Query $kql -First 1000 -SkipToken $page.SkipToken }
}
$rows.Count
$rows | Group-Object power -NoElement
Search-AzGraph -Query "Resources | summarize count() by type | top 3 by count_"
PSResourceGraphResponse`1
4

Count Name
----- ----
    3 PowerState/running
    1 PowerState/deallocated

type                                         count_
----                                         ------
microsoft.network/networkinterfaces              41
microsoft.compute/disks                          38
microsoft.compute/virtualmachines                 4

How to verify: compare $rows.Count with a KQL | count query; for EC2, compare with the console's instance count for the same region and filter. Common mistake: exporting Search-AzGraph or Get-AzVM output straight to CSV — you get type names and @{…} blobs. Production use: a nightly job runs Resource Graph / Describe queries, shapes them into flat OpsKit.CloudResource rows (Module 8), writes JSON for machines and CSV for humans, and compares today with yesterday for drift.

Goal: Produce a flat VM report from both sample files. Environment: pwsh only. Cost: none.

Create the samples with the first block of the Commands tab.
One table for both clouds: build rows with the same columns (Cloud, Name, Env, Size, State) from both files and sort them.
$ec2 = Get-Content ~/pslab/tmp/ec2-describe.json -Raw | ConvertFrom-Json
$arg = Get-Content ~/pslab/tmp/arg-vms.json -Raw | ConvertFrom-Json
$rows = @(
    $ec2.Reservations.Instances | Select-Object @{ n='Cloud'; e={ 'aws' } },
        @{ n='Name'; e={ ($_.Tags | Where-Object Key -eq 'Name').Value } },
        @{ n='Env';  e={ ($_.Tags | Where-Object Key -eq 'env').Value } },
        @{ n='Size'; e={ $_.InstanceType } }, @{ n='State'; e={ $_.State.Name } }
    $arg.data | Select-Object @{ n='Cloud'; e={ 'azure' } }, @{ n='Name'; e={ $_.name } },
        @{ n='Env';  e={ $_.tags.env } }, @{ n='Size'; e={ $_.properties.hardwareProfile.vmSize } },
        @{ n='State'; e={ $_.properties.extended.instanceView.powerState.code -replace '^PowerState/' } }
)
$rows | Sort-Object Env, Name | Format-Table
Cloud Name   Env     Size            State
----- ----   ---     ----            -----
azure web-01 dev     Standard_B1s    running
azure api-01 prod    Standard_D2s_v5 running
azure web-01 prod    Standard_B2s    running
azure web-02 prod    Standard_B2s    deallocated
aws   api-01 staging t3.small        running
aws   db-01  staging r6i.large       stopped
aws   web-01 staging t3.small        running
Summaries: count by Cloud, State with Group-Object Cloud, State -NoElement; list everything not running.
Export and round-trip: $rows | Export-Csv ~/pslab/tmp/fleet.csv and $rows | ConvertTo-Json | Set-Content ~/pslab/tmp/fleet.json; re-import both and confirm 7 rows each.
Cleanup: Remove-Item ~/pslab/tmp/*.csv, ~/pslab/tmp/fleet.json (keep the two samples for Module 5's offline practice).

Case 1: the compliance CSV nobody could filter

Problem: An audit export of “all VMs with tags” had one column Tags containing System.Collections.Generic.Dictionary`2[…]. Root cause: Get-AzVM | Export-Csv. Fix: decide the columns (required tags as separate columns), flatten with calculated properties, then export; add a test that fails if any cell starts with @{ or System..

Case 2: “0 stopped instances” that was really 1

Problem: A dashboard showed one stopped instance in an account that had none. Root cause: @($resp.Reservations.Instances | Where-Object …).Count was fine, but another metric used @($resp.Reservations.Instances).Count on an empty account → 1. Fix: count with .Count on the enumerated result or pipe through Measure-Object; test the empty case explicitly.

Case 3: the inventory job that throttled ARM for everyone

Problem: A tenant-wide VM inventory using Get-AzVM -Status across 80 subscriptions ran for 40 minutes and caused 429s for other automation. Root cause: per-VM instance-view calls. Fix: one Resource Graph query with paging; the job now runs in under a minute and makes a handful of calls.

Common errors and fixes

CSV shows @{…} or System.Object[]

Fix: flatten first; join arrays: @{ n='roles'; e={ $_.Role -join ';' } }.

WARNING: Resulting JSON is truncated …
ConvertTo-Json -Depth 10
Search-AzGraph: Please provide a valid tenant or a valid subscription / no results

Cause: not signed in, wrong tenant, or no read access in the queried scope. Fix: Get-AzContext; pass -Subscription or -ManagementGroup explicitly.

Only 100 (or 1,000) Resource Graph rows

Cause: default page size / no SkipToken loop. Fix: -First 1000 + loop on .SkipToken.

Property is empty although the JSON has it

Cause: case or name mismatch (properties vs Properties is fine in PowerShell, but @odata.nextLink needs quotes: $r.'@odata.nextLink'), or the value is one level deeper than you think. Fix: $x | ConvertTo-Json -Depth 3 to look at the real shape.

Command-line exercises
1. From the EC2 sample, list each instance ID with all its tags as one key=value;… string.
$ec2.Reservations.Instances | Select-Object InstanceId,
    @{ n = 'Tags'; e = { ($_.Tags | ForEach-Object { "$($_.Key)=$($_.Value)" }) -join ';' } }
2. Write a KQL query that counts VMs by env tag, putting untagged VMs under “(none)”.
Resources
| where type =~ 'microsoft.compute/virtualmachines'
| extend env = iff(isempty(tostring(tags.env)), '(none)', tostring(tags.env))
| summarize count() by env
Scenario analysis
Management wants a weekly “owner and cost center per VM” report for Azure and AWS. Design it.

Inputs: Resource Graph (one KQL query, paged) and Get-EC2Instance per enabled region (server-side filters). Shape both into one object model (Cloud, Account/Subscription, Region, Name, Owner, CostCenter, State, Id) — exactly what Get-OpsCloudInventory does in Module 8. Write JSON (machine-readable, kept for week-over-week comparison) and CSV (for people). Flag rows with missing owner/cost center as a separate section. Run read-only identities, schedule outside peak hours, and log row counts per source so a silently empty source is noticed.

Verified teaching videos

▶
PowerShell Master Class - Data and Objects — John Savill's Technical Training
English · objects, JSON/CSV, shaping data
▶
Get Familiar with Microsoft Azure Resource Graph — Tim Warner
English · what Resource Graph is and how to query it

Official documentation

Video storyboard (about 90 seconds)

These materials cannot generate video or MP3 directly; the storyboard and narration are provided for a video tool.

Shot 1 · 0–20s
Visual: a JSON tree with five levels collapses into a flat table row.
Narration: APIs speak trees; reports speak rows.
Shot 2 · 20–45s
Visual: Reservations box opens into Instances; tags list becomes Name and Env columns.
Narration: unwrap lists, pick nested values with calculated properties.
Shot 3 · 45–70s
Visual: a CSV cell showing @{env=prod…} gets a red cross.
Narration: flatten before you export, and give JSON a depth.
Shot 4 · 70–90s
Visual: 80 subscription icons, one KQL query, one answer.
Narration: for inventory, ask Resource Graph once instead of every API many times.
or score ≥ 70% on the Quiz

Module 8 · OpsKit v0.5: Invoke-OpsApi and Get-OpsCloudInventory

50:00 – 60:00 · Everything from this lesson, packaged: an API client that gets its token safely, retries only what should be retried, honors Retry-After, pages, and previews writes — and an inventory function that turns the local file, the API, Azure and AWS into one object model. Both run for real against the mock API.
10 minMock API · real outputsOpsKit 0.4.0 → 0.5.0★★★★★
Learning objectives
  • Add two public functions and one private helper to the OpsKit module and bump the manifest to 0.5.0 with Update-PSModuleManifest.
  • Implement Invoke-OpsApi: token from SecretManagement or $env:OPSKIT_API_TOKEN; loopback-only plain HTTP; -SkipHttpErrorCheck-based classification; exponential backoff overridden by Retry-After; POST retried only on request; -All pagination; ShouldProcess for writes; a clear terminating error.
  • Implement Get-OpsCloudInventory: OpsKit.CloudResource objects with a common Key from Local / Api / Azure / Aws sources; cloud sources skip with a warning when unavailable.
  • Use the interactive troubleshooting tree to diagnose API automation failures.
Prerequisites: Modules 1–7; OpsKit v0.4 in ~/pslab/OpsKit. Importance:★★★★★

What: OpsKit v0.5 layout

FileNew in 0.5Role
Private/Get-OpsApiToken.ps1✓SecureString token: SecretManagement secret OpsKitApiToken → $env:OPSKIT_API_TOKEN → $null; logs only the source
Public/Invoke-OpsApi.ps1✓The REST client used by everything else
Public/Get-OpsCloudInventory.ps1✓Merged inventory; read-only
OpsKit.psd10.5.0, two exports addedUpdate-PSModuleManifest (PSResourceGet)
Public/Get-OpsServer.ps1, Get-OpsConfig.ps1, … (v0.1–v0.4)—Reused: Get-OpsServer is the Local source

Why: design decisions, each from an earlier module

DecisionReason (module)
-SkipHttpErrorCheck -StatusCodeVariable -ResponseHeadersVariable instead of try/catchHTTP errors are terminating; we want to classify, not catch (M1)
Retry set 408/429/500/502/503/504 + network errors; no built-in -MaximumRetryCountBuilt-in retries 404 and POST but not timeouts (M2)
Retry-After overrides backoff 0.5 × 2^(n−1)Throttling (M2)
POST retried only with -RetryNonIdempotentDuplicate creates (M2 case 3)
Token as SecureString, never logged; plain HTTP only for [uri]::IsLoopbackSecrets (M3)
ShouldProcess for non-GET; GETs always runPreviewable changes (M6)
Cloud sources: check module + sign-in, warn and skip; never promptContexts and credentials (M4, M5); non-interactive jobs (Lesson 1)
One object type with a Key (env/name)Shaping and comparing (M7); the integrated lab joins on it

How: the error contract

On final failure Invoke-OpsApi throws a terminating error with id OpsApi.Http<status> (e.g. OpsApi.Http401, OpsApi.Http0 for network errors) and a message <METHOD> <url> failed after N attempt(s): <API message>. Callers can catch it, and logs say what, where and how often — the three things you need at 3 a.m.

When: use Invoke-OpsApi vs Az/AWS cmdlets

Use the vendor modules for Azure and AWS (they handle auth, retries and paging for their APIs). Use Invoke-OpsApi for your own and third-party REST APIs (CMDB, ticketing, monitoring, the mock). For an ARM endpoint that has no cmdlet yet, Invoke-AzRestMethod reuses the Az context.

Common misconceptions① “A wrapper should catch everything and return $null” — callers cannot tell “empty” from “broken”; throw on failure. ② “Retry forever, it will come back” — cap attempts and total time. ③ “The token can be a parameter” — a [string]$Token parameter ends up in history and logs; read it inside. ④ “-Verbose on the script shows the retries” — not inside a module unless passed (M6); the integrated lab passes it. ⑤ “Skipping Azure silently is friendly” — warn, so an empty source is visible.

Invoke-OpsApi internals

Build URIBaseUri + Path ShouldProcessnon-GET only Get-OpsApiTokensecret → env → none Loopback?allow http only there SendSkipHttpErrorCheck Classify<400 → ok · 408/429/5xx/network → retryother 4xx → fail now WaitRetry-After, else 0.5·2^(n−1)attempt ≤ MaxRetries ThrowTerminatingErrorOpsApi.Http<status>"… failed after N attempt(s): msg" -All and value present?emit value items · uri = nextLinknextLink null → done Get-OpsCloudInventoryLocal: Get-OpsServer · Api: Invoke-OpsApi -AllAzure: Search-AzGraph · Aws: Get-EC2Instance → OpsKit.CloudResource
Figure 7-13: the retry loop lives inside the paging loop; each page gets its own attempts

Invoke-OpsApi flow

Every scenario below is a real run from the Commands tab or the integrated lab. Below the animation is the interactive troubleshooting tree.

Ready.

Interactive troubleshooting tree: my API / cloud automation fails

Command table

CommandPurpose
Invoke-OpsApi /api/secure/servers -AllAll items of a paged endpoint
Invoke-OpsApi $p -Method Put -Body $o [-WhatIf]A previewable write
Invoke-OpsApi $p -Method Post -Body $o -RetryNonIdempotentRetry a create on purpose (idempotent server side)
Invoke-OpsApi $p -NoAuth -MaxRetries 2 -TimeoutSec 5Public endpoint, tight budget
$env:OPSKIT_API_URL / $env:OPSKIT_API_TOKENPoint at another API / CI token
Get-OpsCloudInventory [-Source Local,Api,Azure,Aws] [-Env prod]Merged inventory
Update-PSModuleManifest -Path … -ModuleVersion 0.5.0 -FunctionsToExport …Bump the module

Private/Get-OpsApiToken.ps1

function Get-OpsApiToken {
    # Private helper: returns the API token as a SecureString, or $null.
    # Order: 1) a SecretManagement secret (when the module and a vault are available),
    #        2) the environment variable OPSKIT_API_TOKEN (CI pipelines inject it).
    # The token is never written to output, logs or verbose messages.
    [CmdletBinding()]
    [OutputType([securestring])]
    param(
        [string]$SecretName = 'OpsKitApiToken',
        [string]$Vault
    )
    if (Get-Command -Name Get-Secret -Module Microsoft.PowerShell.SecretManagement -ErrorAction Ignore) {
        try {
            $p = @{ Name = $SecretName; ErrorAction = 'Stop' }
            if ($Vault) { $p.Vault = $Vault }
            $secret = Get-Secret @p
            if ($secret -is [securestring]) {
                Write-Verbose "API token: SecretManagement secret '$SecretName'"
                return $secret
            }
        }
        catch {
            Write-Verbose "API token: no secret '$SecretName' ($($_.Exception.Message))"
        }
    }
    if ($env:OPSKIT_API_TOKEN) {
        Write-Verbose 'API token: environment variable OPSKIT_API_TOKEN'
        return ConvertTo-SecureString -String $env:OPSKIT_API_TOKEN -AsPlainText -Force
    }
    Write-Verbose 'API token: none found'
    $null
}

Public/Invoke-OpsApi.ps1

function Invoke-OpsApi {
    <#
    .SYNOPSIS
        Calls a JSON REST API with bearer auth, retries with backoff, and pagination.
    .DESCRIPTION
        A thin wrapper around Invoke-RestMethod for OpsKit:
        - the bearer token comes from SecretManagement (secret 'OpsKitApiToken') or
          $env:OPSKIT_API_TOKEN, never from a parameter typed in clear text;
        - only transient failures are retried (408, 429, 500, 502, 503, 504 and
          network errors/timeouts); Retry-After is honored, otherwise the wait doubles;
        - POST is retried only with -RetryNonIdempotent;
        - -All follows 'nextLink' and returns the items of every page;
        - every change (non-GET) goes through ShouldProcess (-WhatIf / -Confirm).
    .PARAMETER Path
        A path relative to -BaseUri ('/api/servers') or an absolute URL.
    .PARAMETER BaseUri
        Default: $env:OPSKIT_API_URL, otherwise http://127.0.0.1:5050.
    .EXAMPLE
        Invoke-OpsApi /api/secure/servers -All | Group-Object Env -NoElement
    .EXAMPLE
        Invoke-OpsApi /api/secure/servers -Method Post -Body @{ Name = 'web-03'; Env = 'prod' } -WhatIf
    #>
    [CmdletBinding(SupportsShouldProcess)]
    param(
        [Parameter(Mandatory, Position = 0)]
        [string]$Path,

        [ValidateSet('Get', 'Post', 'Put', 'Patch', 'Delete')]
        [string]$Method = 'Get',

        [object]$Body,

        [string]$BaseUri = $(if ($env:OPSKIT_API_URL) { $env:OPSKIT_API_URL } else { 'http://127.0.0.1:5050' }),

        [switch]$All,

        [switch]$NoAuth,

        [ValidateRange(0, 10)]
        [int]$MaxRetries = 4,

        [ValidateRange(0.1, 60)]
        [double]$BaseDelaySec = 0.5,

        [ValidateRange(1, 300)]
        [int]$TimeoutSec = 15,

        [switch]$RetryNonIdempotent
    )

    $uri = if ($Path -match '^https?://') { $Path } else { $BaseUri.TrimEnd('/') + '/' + $Path.TrimStart('/') }
    if ($Method -ne 'Get' -and -not $PSCmdlet.ShouldProcess($uri, "HTTP $($Method.ToUpper())")) { return }

    $request = @{
        Method              = $Method
        TimeoutSec          = $TimeoutSec
        SkipHttpErrorCheck  = $true          # we inspect the status code ourselves
        ErrorAction         = 'Stop'
    }
    if ($null -ne $Body) {
        $request.Body        = if ($Body -is [string]) { $Body } else { $Body | ConvertTo-Json -Depth 10 -Compress }
        $request.ContentType = 'application/json'
    }
    if (-not $NoAuth) {
        $token = Get-OpsApiToken
        if ($token) {
            $request.Authentication = 'Bearer'
            $request.Token          = $token
            # Plain HTTP is accepted only for the local lab API, never for a remote host.
            if (([uri]$uri).IsLoopback) { $request.AllowUnencryptedAuthentication = $true }
        }
    }
    $transient = 408, 429, 500, 502, 503, 504
    $canRetry  = $Method -ne 'Post' -or $RetryNonIdempotent

    while ($uri) {
        $attempt = 0
        while ($true) {
            $attempt++
            $status = 0; $headers = $null; $failure = $null
            try {
                $response = Invoke-RestMethod -Uri $uri @request -StatusCodeVariable status -ResponseHeadersVariable headers
            }
            catch {
                $failure = $_.Exception.Message        # DNS, refused connection, timeout
            }
            if (-not $failure -and $status -lt 400) { break }

            $retryable = $canRetry -and ($failure -or $status -in $transient)
            $what = if ($failure) { $failure } else { "HTTP $status $($response.error.message)".Trim() }
            if (-not $retryable -or $attempt -gt $MaxRetries) {
                $msg = "$($Method.ToUpper()) $uri failed after $attempt attempt(s): $what"
                $err = [System.Management.Automation.ErrorRecord]::new(
                    [System.Net.Http.HttpRequestException]::new($msg), "OpsApi.Http$status",
                    [System.Management.Automation.ErrorCategory]::ConnectionError, $uri)
                $PSCmdlet.ThrowTerminatingError($err)
            }
            $delay = $BaseDelaySec * [math]::Pow(2, $attempt - 1)
            $retryAfter = if ($headers -and $headers['Retry-After']) { "$($headers['Retry-After'])" }
            if ($retryAfter -match '^\d+$') { $delay = [double]$retryAfter }
            Write-Verbose ("Attempt {0} -> {1}; waiting {2:0.0}s" -f $attempt, $what, $delay)
            Start-Sleep -Milliseconds ([int]($delay * 1000))
        }

        if ($All -and $null -ne $response.value) {
            $response.value                     # emit the items, one by one
            $uri = $response.nextLink           # $null on the last page ends the loop
        }
        else {
            $response
            $uri = $null
        }
    }
}

Public/Get-OpsCloudInventory.ps1

function Get-OpsCloudInventory {
    <#
    .SYNOPSIS
        Merges the OpsKit inventory with API, Azure and AWS sources into one object model.
    .DESCRIPTION
        Returns one OpsKit.CloudResource per server and source. Sources:
          Local  - Get-OpsServer (inventory.json)
          Api    - the inventory API through Invoke-OpsApi (bearer token, retries, paging)
          Azure  - Azure Resource Graph (needs Az.ResourceGraph and Connect-AzAccount)
          Aws    - EC2 (needs AWS.Tools.EC2 and a profile or role)
        A cloud source that is not installed or not signed in is skipped with a warning;
        it never prompts. Everything is read-only.
    .EXAMPLE
        Get-OpsCloudInventory | Group-Object Source -NoElement
    .EXAMPLE
        Get-OpsCloudInventory -Source Local, Api -Env prod | Format-Table
    #>
    [CmdletBinding()]
    [OutputType('OpsKit.CloudResource')]
    param(
        [ValidateSet('Local', 'Api', 'Azure', 'Aws')]
        [string[]]$Source = @('Local', 'Api'),

        [ValidateSet('dev', 'staging', 'prod')]
        [string]$Env,

        [string]$AwsRegion = 'ca-central-1',

        [ValidateRange(0, 10)]
        [int]$MaxRetries = 4
    )

    function New-Resource($Name, $Env, $Region, $IP, $State, $Source, $Id) {
        [pscustomobject]@{
            PSTypeName = 'OpsKit.CloudResource'
            Key        = "$Env/$Name".ToLowerInvariant()
            Name       = $Name
            Env        = $Env
            Region     = $Region
            IP         = $IP
            State      = $State
            Source     = $Source
            Id         = $Id
        }
    }

    if ('Local' -in $Source) {
        $p = @{}; if ($Env) { $p.Env = $Env }
        foreach ($s in Get-OpsServer @p) {
            New-Resource $s.Name $s.Env $s.Region $s.IP 'declared' 'Local' "local:$($s.Env)/$($s.Name)"
        }
    }

    if ('Api' -in $Source) {
        $path = '/api/secure/servers?pageSize=5' + $(if ($Env) { "&env=$Env" })
        foreach ($s in Invoke-OpsApi $path -All -MaxRetries $MaxRetries) {
            $state = if ($s.Monitored) { 'monitored' } else { 'unmonitored' }
            New-Resource $s.Name $s.Env $s.Region $s.IP $state 'Api' "api:$($s.Env)/$($s.Name)"
        }
    }

    if ('Azure' -in $Source) {
        if (-not (Get-Module -ListAvailable -Name Az.ResourceGraph)) {
            Write-Warning 'Azure source skipped: module Az.ResourceGraph is not installed.'
        }
        elseif (-not (Get-AzContext -ErrorAction Ignore)) {
            Write-Warning 'Azure source skipped: no Az context (run Connect-AzAccount first).'
        }
        else {
            $kql = @'
Resources
| where type =~ 'microsoft.compute/virtualmachines'
| extend env = tostring(tags.env), power = tostring(properties.extended.instanceView.powerState.code)
| project name, env, location, id, power
'@
            if ($Env) { $kql += "`n| where env =~ '$Env'" }
            $page = Search-AzGraph -Query $kql -First 1000
            while ($page) {
                foreach ($vm in $page) {
                    New-Resource $vm.name $vm.env $vm.location $null ($vm.power -replace '^PowerState/') 'Azure' $vm.id
                }
                $page = if ($page.SkipToken) { Search-AzGraph -Query $kql -First 1000 -SkipToken $page.SkipToken }
            }
        }
    }

    if ('Aws' -in $Source) {
        if (-not (Get-Module -ListAvailable -Name AWS.Tools.EC2)) {
            Write-Warning 'AWS source skipped: module AWS.Tools.EC2 is not installed.'
        }
        else {
            try {
                $filter = if ($Env) { @{ Name = 'tag:env'; Values = $Env } }
                $p = @{ Region = $AwsRegion; ErrorAction = 'Stop' }
                if ($filter) { $p.Filter = $filter }
                foreach ($i in (Get-EC2Instance @p).Instances) {
                    $tags = @{}; foreach ($t in $i.Tags) { $tags[$t.Key] = $t.Value }
                    New-Resource $tags['Name'] $tags['env'] $AwsRegion $i.PrivateIpAddress $i.State.Name.Value 'Aws' $i.InstanceId
                }
            }
            catch {
                Write-Warning "AWS source skipped: $($_.Exception.Message)"
            }
        }
    }
}

1. Bump to 0.5.0 and load

Set-Location ~/pslab
Update-PSModuleManifest -Path ./OpsKit/OpsKit.psd1 -ModuleVersion 0.5.0 `
    -FunctionsToExport Get-OpsConfig, Get-OpsServer, Test-OpsEndpoint, Invoke-OpsApi, Get-OpsCloudInventory
Import-Module ./OpsKit -Force
Get-Module OpsKit | Format-Table Name, Version
Get-Command -Module OpsKit -Name *Api*, *Cloud* | Format-Table Name, Version
Name   Version
----   -------
OpsKit 0.5.0

Name                  Version
----                  -------
Get-OpsCloudInventory 0.5.0
Invoke-OpsApi         0.5.0

Add the remaining v0.3/v0.4 functions (Invoke-OpsBackup, Invoke-OpsHealthCheck) to -FunctionsToExport if your module has them — FunctionsToExport replaces the list.

2–3. Token handling and pagination

Remove-Item Env:OPSKIT_API_TOKEN -ErrorAction Ignore
try { Invoke-OpsApi /api/secure/servers } catch { $_.Exception.Message; $_.FullyQualifiedErrorId }

$env:OPSKIT_API_TOKEN = 'lab-token-7f3a'      # lab value; in CI it comes from the secret store
$all = Invoke-OpsApi '/api/secure/servers?pageSize=5' -All -Verbose
$all.Count
GET http://127.0.0.1:5050/api/secure/servers failed after 1 attempt(s): HTTP 401 Missing or invalid bearer token.
OpsApi.Http401,Invoke-OpsApi
VERBOSE: API token: environment variable OPSKIT_API_TOKEN
VERBOSE: WebRequest: v1.1 GET http://127.0.0.1:5050/api/secure/servers with query length 10
VERBOSE: WebResponse: 200 OK with application/json payload with body size 683 B (683 bytes)
VERBOSE: WebRequest: v1.1 GET http://127.0.0.1:5050/api/secure/servers with query length 17
VERBOSE: WebResponse: 200 OK with application/json payload with body size 688 B (688 bytes)
VERBOSE: WebRequest: v1.1 GET http://127.0.0.1:5050/api/secure/servers with query length 17
VERBOSE: WebResponse: 200 OK with application/json payload with body size 286 B (286 bytes)
12

4–5. Transient failures and throttling

Invoke-OpsApi '/flaky?key=m8' -NoAuth -Verbose
Invoke-OpsApi '/ratelimit?key=m8&after=2' -NoAuth -Verbose
VERBOSE: WebRequest: v1.1 GET http://127.0.0.1:5050/flaky with query length 6
VERBOSE: WebResponse: 503 Service Unavailable with application/json payload with body size 74 B (74 bytes)
VERBOSE: Attempt 1 -> HTTP 503 Try again (attempt 1).; waiting 0.5s
VERBOSE: WebRequest: v1.1 GET http://127.0.0.1:5050/flaky with query length 6
VERBOSE: WebResponse: 503 Service Unavailable with application/json payload with body size 74 B (74 bytes)
VERBOSE: Attempt 2 -> HTTP 503 Try again (attempt 2).; waiting 1.0s
VERBOSE: WebRequest: v1.1 GET http://127.0.0.1:5050/flaky with query length 6
VERBOSE: WebResponse: 200 OK with application/json payload with body size 27 B (27 bytes)

status attempt
------ -------
ok           3

VERBOSE: WebRequest: v1.1 GET http://127.0.0.1:5050/ratelimit with query length 14
VERBOSE: WebResponse: 429 Too Many Requests with application/json payload with body size 69 B (69 bytes)
VERBOSE: Attempt 1 -> HTTP 429 Rate limit exceeded.; waiting 2.0s
VERBOSE: WebRequest: v1.1 GET http://127.0.0.1:5050/ratelimit with query length 14
VERBOSE: WebResponse: 200 OK with application/json payload with body size 27 B (27 bytes)

status attempt
------ -------
ok           2

6–7. Permanent errors, giving up, and previewing a write

try { Invoke-OpsApi /api/servers/prod/web-99 -NoAuth -Verbose } catch { $_.Exception.Message }
try { Invoke-OpsApi '/flaky?key=m8b&fail=9' -NoAuth -MaxRetries 2 } catch { $_.Exception.Message }
Invoke-OpsApi /api/secure/servers -Method Post -Body @{ Name = 'web-03'; Env = 'prod' } -WhatIf
VERBOSE: WebRequest: v1.1 GET http://127.0.0.1:5050/api/servers/prod/web-99
VERBOSE: WebResponse: 404 Not Found with application/json payload with body size 77 B (77 bytes)
GET http://127.0.0.1:5050/api/servers/prod/web-99 failed after 1 attempt(s): HTTP 404 Server 'prod/web-99' was not found.
GET http://127.0.0.1:5050/flaky?key=m8b&fail=9 failed after 3 attempt(s): HTTP 503 Try again (attempt 3).
What if: Performing the operation "HTTP POST" on target "http://127.0.0.1:5050/api/secure/servers".

8–9. One object model

$inv = Get-OpsCloudInventory
$inv | Group-Object Source -NoElement
$inv[0] | Format-List
$inv[0].PSObject.TypeNames[0]
Get-OpsCloudInventory -Source Local, Api -Env prod | Sort-Object Key, Source | Format-Table Key, Source, IP, State
Count Name
----- ----
   12 Api
   12 Local

Key    : dev/web-01
Name   : web-01
Env    : dev
Region : canadacentral
IP     : 10.10.1.21
State  : declared
Source : Local
Id     : local:dev/web-01

OpsKit.CloudResource

Key             Source IP         State
---             ------ --         -----
prod/api-01     Api    10.30.1.43 monitored
prod/api-01     Local  10.30.1.43 declared
prod/bastion-01 Api    10.30.2.10 unmonitored
prod/bastion-01 Local  10.30.2.10 declared
prod/db-01      Api    10.30.1.44 unmonitored
prod/db-01      Local  10.30.1.44 declared
prod/edge-01    Api    10.30.2.51 monitored
prod/edge-01    Local  10.30.2.51 declared
prod/web-01     Api    10.30.1.41 monitored
prod/web-01     Local  10.30.1.41 declared
prod/web-02     Api    10.30.1.42 monitored
prod/web-02     Local  10.30.1.42 declared

10. Cloud sources on a machine without Az / AWS.Tools

$env:PSModulePath = Join-Path $PSHOME 'Modules'      # simulate a bare machine (this session only)
Import-Module ~/pslab/OpsKit -Force
Get-OpsCloudInventory -Source Local, Azure, Aws | Group-Object Source -NoElement
WARNING: Azure source skipped: module Az.ResourceGraph is not installed.
WARNING: AWS source skipped: module AWS.Tools.EC2 is not installed.

Count Name
----- ----
   12 Local
# With Az and AWS.Tools installed and signed in to sandboxes:
Get-OpsCloudInventory -Source Local, Api, Azure, Aws | Group-Object Source -NoElement
Count Name
----- ----
   12 Local
   12 Api
    4 Azure
    3 Aws

How to verify: the mock's /stats counters must match the attempts in the verbose log; $inv | Group-Object Key | Where-Object Count -ne 2 is empty when Local and Api agree (verified: 0 groups). Common mistake: forgetting to add the new names to FunctionsToExport — the files load but the commands are “not recognized”. Production use: Lesson 8 adds Pester tests that mock Invoke-RestMethod to return 503/429/404 sequences and assert attempt counts and waits, plus PSScriptAnalyzer and a CI workflow that sets OPSKIT_API_TOKEN from a secret.

Goal: Ship OpsKit v0.5 and prove its behavior against the mock API. Environment: OpsKit v0.4, mock API running. Cost: none.

Add the three files from the Commands tab: ~/pslab/OpsKit/Private/Get-OpsApiToken.ps1, ~/pslab/OpsKit/Public/Invoke-OpsApi.ps1, ~/pslab/OpsKit/Public/Get-OpsCloudInventory.ps1.
Bump and import (block 1). Get-Module OpsKit must show 0.5.0.
Token from env, then (optionally) from SecretStore: run block 2–3; if you did Module 3's SecretStore step, remove the env var and run Invoke-OpsApi /api/secure/servers -Verbose — the first verbose line must say “SecretManagement secret 'OpsKitApiToken'”.
Measure the retry policy: with a Stopwatch, time Invoke-OpsApi '/flaky?key=lab8&fail=3' -NoAuth. Expected: about 0.5 + 1 + 2 = 3.5 s and success on attempt 4 (measured: 3.7 s, attempt 4). Then -MaxRetries 2: failure after 3 attempts.
Prove that POST is not retried by default:
try { Invoke-OpsApi '/flaky?key=lab8post' -Method Post -NoAuth -Confirm:$false } catch { $_.Exception.Message }
Invoke-OpsApi '/flaky?key=lab8post' -Method Post -NoAuth -Confirm:$false -RetryNonIdempotent
POST http://127.0.0.1:5050/flaky?key=lab8post failed after 1 attempt(s): HTTP 503 Try again (attempt 1).

status attempt
------ -------
ok           3
Inventory: run block 8; then start the mock with -Drift (stop it first) and find the two differences with Group-Object Key and IP comparison — that is the integrated lab's starting point.
Cleanup: keep OpsKit 0.5.0 (Lesson 8 builds on it). Stop the mock API (Module 0) when done; Remove-Item Env:OPSKIT_API_TOKEN.

Case 1: a wrapper that hid an outage

Problem: A home-grown Invoke-Api returned $null on any error. During a CMDB outage the nightly sync saw “no servers” and marked 600 servers as decommissioned. Root cause: errors converted to empty results. Fix: throw on failure (as Invoke-OpsApi does); callers decide; and a sanity check (“refuse to sync if the source returned < 50% of yesterday's count”).

Case 2: retries that multiplied load

Problem: Three layers each retried 3 times — the HTTP wrapper, the function using it, and the scheduler — so one failing call became 27 requests. Root cause: retry at every layer. Fix: retry in exactly one place (the client), with a total time budget; upper layers fail fast and report.

Case 3: one inventory, four truths

Problem: The CMDB, Azure, AWS and the monitoring tool disagreed about which servers existed; each team trusted its own export. Root cause: no common key or object model. Fix: a normalized object (Key, Source, State, Id) from every source, then joins and drift reports — exactly Get-OpsCloudInventory plus the integrated lab's sync.

Common errors and fixes

Invoke-OpsApi: The term 'Invoke-OpsApi' is not recognized

Cause: not in FunctionsToExport, or an old OpsKit version loaded first. Fix: Get-Module OpsKit -ListAvailable; Import-Module ~/pslab/OpsKit -Force; check the manifest.

failed after 1 attempt(s): HTTP 401

Cause: no token found or wrong token. Fix: Invoke-OpsApi … -Verbose shows the token source; check $env:OPSKIT_API_TOKEN or Get-SecretInfo OpsKitApiToken.

OpsApi.Http0 … No connection could be made

Cause: API not running / wrong $env:OPSKIT_API_URL. Status 0 means no HTTP response at all. Fix: start the mock (Module 0); Test-NetConnection 127.0.0.1 -Port 5050 on Windows.

WARNING: Azure source skipped: no Az context

Fix: Connect-AzAccount (and Set-AzContext) in the same session before calling; in CI, the login step must run in the same job with enable-AzPSSession: true.

-Verbose on my script shows no retries

Cause: preference does not cross into the module (Module 6). Fix: pass -Verbose:($VerbosePreference -eq 'Continue') to OpsKit calls.

Command-line exercises
1. Get all prod servers through the API with OpsKit and print only their names, sorted.
Invoke-OpsApi '/api/secure/servers?env=prod&pageSize=2' -All | Sort-Object Name | ForEach-Object Name
2. Find servers whose IP differs between Local and Api.
Get-OpsCloudInventory | Group-Object Key | Where-Object { @($_.Group.IP | Select-Object -Unique).Count -gt 1 } |
    ForEach-Object Name
Scenario analysis
A colleague proposes adding [string]$Token to Invoke-OpsApi “for flexibility”. Respond.

A string parameter invites literals on the command line (history file, Module 3), shows up in -Verbose/transcripts if anyone logs bound parameters, and spreads the token through call sites. If flexibility is needed, accept a [securestring] or a secret name (-SecretName) and keep resolution inside Get-OpsApiToken; CI sets OPSKIT_API_TOKEN. Lesson 8 adds PSScriptAnalyzer to catch plain-text credential parameters (e.g. PSAvoidUsingPlainTextForPassword for password-like names) — but do not rely on a linter to catch every token parameter.

Verified teaching videos

▶
Call REST APIs with Invoke-RestMethod in PowerShell — Adam Driscoll
English · the building block Invoke-OpsApi wraps
▶
PowerShell Master Class - Automation — John Savill's Technical Training
English · running such tools unattended

No verified video builds a retrying, paginating REST client module like OpsKit's; this module's code and runs are the reference.

Official documentation

Video storyboard (about 90 seconds)

These materials cannot generate video or MP3 directly; the storyboard and narration are provided for a video tool.

Shot 1 · 0–20s
Visual: an OpsKit box opens; three new files slide in; the version label flips 0.4 → 0.5.
Narration: one client for every API, one inventory for every source.
Shot 2 · 20–50s
Visual: the flow chart lights up: token, loopback check, send, classify, wait, next page.
Narration: secure token, transient-only retries, Retry-After, pagination, preview for writes.
Shot 3 · 50–75s
Visual: Local and Api rows interleave in one table keyed by env/name; Azure and AWS badges show “skipped” warnings.
Narration: same object, any source; missing sources warn instead of hiding.
Shot 4 · 75–90s
Visual: a red error line “failed after 3 attempt(s): HTTP 503”.
Narration: when it fails, it says what, where and how often.
or score ≥ 70% on the Quiz

Command cheat sheet

All Lesson 7 key points: HTTP cmdlets, errors, paging and retries, secrets, Az, AWS.Tools, idempotent changes, shaping, OpsKit v0.5
PowerShell 7.6Copyable

1. Invoke-RestMethod / Invoke-WebRequest

$o = Invoke-RestMethod $uri                       # JSON → PSCustomObject
$r = Invoke-WebRequest $uri; $r.StatusCode; $r.Headers['Content-Type'][0]
Invoke-RestMethod $uri -Method Post -ContentType 'application/json' `
  -Body ($obj | ConvertTo-Json -Depth 10)          # never default depth 2
-StatusCodeVariable sc -ResponseHeadersVariable h
$h['Location'][0]                                 # header values are String[]

2. HTTP errors

try { Invoke-RestMethod $uri }                    # 4xx/5xx = terminating
catch {
  [int]$_.Exception.Response.StatusCode
  ($_.ErrorDetails.Message | ConvertFrom-Json).error.message
}
$b = Invoke-RestMethod $uri -SkipHttpErrorCheck -StatusCodeVariable sc
# -ErrorAction SilentlyContinue does NOT hide HTTP errors

3. Paging, retries, timeouts

(Invoke-RestMethod $uri -FollowRelLink).value     # Link: rel="next"
$all = while ($u) { $r = irm $u; $r.value; $u = $r.nextLink }
-MaximumRetryCount 3 -RetryIntervalSec 2   # retries ALL >=400 (404, POST!)
                                           # 429 honors Retry-After; no retry on timeout/refused
-TimeoutSec 30                  # = -ConnectionTimeoutSeconds (until headers)
-OperationTimeoutSeconds 30     # stalls while reading the body

4. Tokens and secrets

$t = ConvertTo-SecureString $env:API_TOKEN -AsPlainText -Force
Invoke-RestMethod $uri -Authentication Bearer -Token $t   # https only
#   -AllowUnencryptedAuthentication   → loopback labs only
Get-Secret OpsKitApiToken; Set-Secret -Name n -Secret $v
Get-SecretInfo; Register-SecretVault -Name S -ModuleName Microsoft.PowerShell.SecretStore
Set-SecretStoreConfiguration -Interaction None …; Unlock-SecretStore -Password $p
(Get-PSReadLineOption).AddToHistoryHandler.Invoke($line)  # saved to file?

5. Az

Disable-AzContextAutosave -Scope Process
Connect-AzAccount -Identity                      # managed identity
Connect-AzAccount -ServicePrincipal -ApplicationId $a -Tenant $t -CertificateThumbprint $th
Connect-AzAccount -ApplicationId $a -Tenant $t -FederatedToken $jwt   # OIDC
Set-AzContext -Subscription $id; (Get-AzContext).Subscription.Id   # guard!
Get-AzResourceGroup -Tag @{owner='x'}; Get-AzVM -Status
New-AzResourceGroup … -WhatIf; az … --output json | ConvertFrom-Json

6. AWS.Tools

Install-AWSToolsModule EC2, S3, SecurityToken -Cleanup
aws sso login --profile p; Set-AWSCredential -ProfileName p
Set-DefaultAWSRegion -Region ca-central-1        # or -Region per call
Get-STSCallerIdentity                            # who am I?
(Get-EC2Instance -Filter @{Name='tag:env';Values='prod'}).Instances
Get-EC2Instance -Select '*' / -NoAutoIteration -NextToken $t
Get-S3Bucket

7. Idempotent changes and shaping

GET → compare → if ($PSCmdlet.ShouldProcess($t,$a)) { PUT } → report Changed
catch [Microsoft.PowerShell.Commands.HttpResponseException] { 404 → $null; else throw }
Update-AzTag -ResourceId $id -Tag $t -Operation Merge
Mod-Function @{ WhatIf=$WhatIfPreference; Verbose=$VerbosePreference -eq 'Continue' }
$x.Reservations.Instances | Select-Object Id, @{n='Name';e={($_.Tags|? Key -eq Name).Value}}
$none.List.Count  # not @($none.List).Count (empty → 1!)
Search-AzGraph -Query $kql -First 1000 [-SkipToken $p.SkipToken]

8. OpsKit v0.5

Import-Module ~/pslab/OpsKit -Force             # 0.5.0
$env:OPSKIT_API_TOKEN / secret 'OpsKitApiToken' / $env:OPSKIT_API_URL
Invoke-OpsApi /api/secure/servers -All -Verbose
Invoke-OpsApi $p -Method Put -Body $o -WhatIf
Invoke-OpsApi $p -Method Post -Body $o -RetryNonIdempotent
Get-OpsCloudInventory -Source Local, Api, Azure, Aws -Env prod
./scripts/Sync-OpsInventory.ps1 -WhatIf; $LASTEXITCODE   # 0 / 1 / 2

Integrated lab + final quiz

Write ~/pslab/scripts/Sync-OpsInventory.ps1: make the inventory API match inventory.json while the API injects 503 and 429 faults and has drifted — preview with -WhatIf, apply with retries, prove idempotency, and return exit codes a scheduler can act on
about 25 minLocal onlyIntegrates M1–M8

Scenario

The “cloud” (the mock API) has drifted from the source of truth: prod/bastion-01 is missing and dev/db-01 has the wrong IP. Every third authenticated request fails (503 and 429 alternately). Write a sync script that: reads both sides with OpsKit; plans Create, Update or Unmanaged per server; previews with -WhatIf; applies through Invoke-OpsApi; writes a JSON report even in -WhatIf mode; and exits 0 when in sync, 1 when drift remains, 2 when the API cannot be read.

Start the mock API with faults and drift (stop any running copy first, Module 0):
Set-Location ~/pslab
$api = Start-ThreadJob { & ~/pslab/Start-MockApi.ps1 -FailEvery 3 -Drift }
Start-Sleep -Seconds 1
$env:OPSKIT_API_TOKEN = 'lab-token-7f3a'
Import-Module ./OpsKit -Force
The script (M1–M3, M6, M8) — save as ~/pslab/scripts/Sync-OpsInventory.ps1:
<#
.SYNOPSIS
    Makes the inventory API match ~/pslab/data/inventory.json (the source of truth).
.DESCRIPTION
    Reads both sides with Get-OpsCloudInventory, then for every server:
      missing in the API      -> Create  (POST,  through ShouldProcess)
      IP or Region different  -> Update  (PUT,   through ShouldProcess)
      only in the API         -> Unmanaged (reported, never deleted automatically)
    Writes a JSON report. Exit codes:
      0  in sync (after applying changes, if any)
      1  drift remains (-WhatIf, a failed change, or unmanaged servers)
      2  the API could not be read (network, auth, retries exhausted)
.EXAMPLE
    ./Sync-OpsInventory.ps1 -WhatIf
    ./Sync-OpsInventory.ps1 -Verbose; $LASTEXITCODE
#>
#Requires -Version 7.4
[CmdletBinding(SupportsShouldProcess)]
param(
    [string]$ReportPath = (Join-Path $HOME 'pslab' 'tmp' 'sync-report.json'),
    [ValidateRange(0, 10)]
    [int]$MaxRetries = 4
)
Import-Module (Join-Path $HOME 'pslab' 'OpsKit') -Force -ErrorAction Stop -Verbose:$false
# -Verbose sets $VerbosePreference in this script only; module functions do not see it.
$vb = @{ Verbose = $VerbosePreference -eq 'Continue' }

try {
    $local  = Get-OpsCloudInventory -Source Local @vb
    $remote = Get-OpsCloudInventory -Source Api -MaxRetries $MaxRetries @vb
}
catch {
    Write-Error "Sync aborted, API not readable: $($_.Exception.Message)"
    exit 2
}

$remoteByKey = @{}
foreach ($r in $remote) { $remoteByKey[$r.Key] = $r }
$servers = @(Get-OpsServer)          # full records (Monitored, Port …) for the request bodies

$results = foreach ($l in $local) {
    $r = $remoteByKey[$l.Key]
    $remoteByKey.Remove($l.Key)
    $action = if (-not $r) { 'Create' }
              elseif ($r.IP -ne $l.IP -or $r.Region -ne $l.Region) { 'Update' }
              else { 'None' }
    $detail = switch ($action) {
        'Create' { 'missing in API' }
        'Update' { "API has IP=$($r.IP) Region=$($r.Region)" }
        default  { '' }
    }
    $result = 'InSync'
    if ($action -ne 'None') {
        $s = $servers | Where-Object { $_.Env -eq $l.Env -and $_.Name -eq $l.Name }
        $body = @{ Name = $s.Name; Env = $s.Env; Region = $s.Region; IP = $s.IP; Monitored = $s.Monitored }
        if ($PSCmdlet.ShouldProcess($l.Key, "$action in inventory API")) {
            try {
                if ($action -eq 'Create') {
                    $null = Invoke-OpsApi /api/secure/servers -Method Post -Body $body -RetryNonIdempotent -MaxRetries $MaxRetries -Confirm:$false @vb
                }
                else {
                    $null = Invoke-OpsApi "/api/secure/servers/$($l.Env)/$($l.Name)" -Method Put -Body $body -MaxRetries $MaxRetries -Confirm:$false @vb
                }
                $result = 'Done'
            }
            catch {
                $result = 'Failed'; $detail = $_.Exception.Message
            }
        }
        else { $result = 'WhatIf' }
    }
    [pscustomobject]@{ Key = $l.Key; Action = $action; Result = $result; Detail = $detail }
}
$results = @($results) + @(foreach ($k in $remoteByKey.Keys) {
    [pscustomobject]@{ Key = $k; Action = 'Unmanaged'; Result = 'Review'; Detail = 'only in API' }
})

$report = [pscustomobject]@{
    Time    = (Get-Date).ToUniversalTime().ToString('o')
    Changes = @($results | Where-Object Action -ne 'None').Count
    Results = $results
}
$report | ConvertTo-Json -Depth 4 | Set-Content -LiteralPath $ReportPath -WhatIf:$false   # report even with -WhatIf
$results | Where-Object Action -ne 'None'

$open = @($results | Where-Object Result -in 'WhatIf', 'Failed', 'Review')
if ($open.Count) {
    Write-Warning "$($open.Count) item(s) not in sync: $($open.Key -join ', ')"
    exit 1
}
Write-Verbose "In sync: $(@($results).Count) servers checked"
exit 0

Note the three verified traps handled here: -WhatIf would also skip Set-Content of the report (hence -WhatIf:$false); -Verbose would not reach OpsKit (hence @vb); and the module calls get -Confirm:$false because the script already asked ShouldProcess.

1. Preview:
./scripts/Sync-OpsInventory.ps1 -WhatIf; "exit=$LASTEXITCODE"
What if: Performing the operation "Update in inventory API" on target "dev/db-01".
What if: Performing the operation "Create in inventory API" on target "prod/bastion-01".

WARNING: 2 item(s) not in sync: dev/db-01, prod/bastion-01
Key             Action Result Detail
---             ------ ------ ------
dev/db-01       Update WhatIf API has IP=10.10.1.99 Region=canadacentral
prod/bastion-01 Create WhatIf missing in API

exit=1
2. Apply, watching the retries:
./scripts/Sync-OpsInventory.ps1 -Verbose; "exit=$LASTEXITCODE"
VERBOSE: Reading C:\Users\labadmin\pslab\data\inventory.json
VERBOSE: API token: environment variable OPSKIT_API_TOKEN
VERBOSE: WebRequest: v1.1 GET http://127.0.0.1:5050/api/secure/servers with query length 10
VERBOSE: WebResponse: 200 OK with application/json payload with body size 683 B (683 bytes)
VERBOSE: WebRequest: v1.1 GET http://127.0.0.1:5050/api/secure/servers with query length 17
VERBOSE: WebResponse: 429 Too Many Requests with application/json payload with body size 69 B (69 bytes)
VERBOSE: Attempt 1 -> HTTP 429 Injected rate limit.; waiting 1.0s
VERBOSE: WebRequest: v1.1 GET http://127.0.0.1:5050/api/secure/servers with query length 17
VERBOSE: WebResponse: 200 OK with application/json payload with body size 688 B (688 bytes)
VERBOSE: WebRequest: v1.1 GET http://127.0.0.1:5050/api/secure/servers with query length 17
VERBOSE: WebResponse: 200 OK with application/json payload with body size 162 B (162 bytes)
VERBOSE: Performing the operation "Update in inventory API" on target "dev/db-01".
VERBOSE: Performing the operation "HTTP PUT" on target "http://127.0.0.1:5050/api/secure/servers/dev/db-01".
VERBOSE: API token: environment variable OPSKIT_API_TOKEN
VERBOSE: WebRequest: v1.1 PUT http://127.0.0.1:5050/api/secure/servers/dev/db-01 with application/json payload with body size 89 B (89 bytes)
VERBOSE: WebResponse: 503 Service Unavailable with application/json payload with body size 67 B (67 bytes)
VERBOSE: Attempt 1 -> HTTP 503 Injected fault.; waiting 0.5s
VERBOSE: WebRequest: v1.1 PUT http://127.0.0.1:5050/api/secure/servers/dev/db-01 with application/json payload with body size 89 B (89 bytes)
VERBOSE: WebResponse: 200 OK with application/json payload with body size 113 B (113 bytes)
VERBOSE: Performing the operation "Create in inventory API" on target "prod/bastion-01".
VERBOSE: Performing the operation "HTTP POST" on target "http://127.0.0.1:5050/api/secure/servers".
VERBOSE: API token: environment variable OPSKIT_API_TOKEN
VERBOSE: WebRequest: v1.1 POST http://127.0.0.1:5050/api/secure/servers with application/json payload with body size 94 B (94 bytes)
VERBOSE: WebResponse: 201 Created with application/json payload with body size 94 B (94 bytes)

VERBOSE: In sync: 12 servers checked
Key             Action Result Detail
---             ------ ------ ------
dev/db-01       Update Done   API has IP=10.10.1.99 Region=canadacentral
prod/bastion-01 Create Done   missing in API

exit=0

The 429 on page 2 and the 503 on the PUT were absorbed by Invoke-OpsApi; the POST was allowed to retry because the script passes -RetryNonIdempotent — safe here because the API answers 409 for an existing server, so a duplicate cannot be created.

3. Idempotency, an unmanaged server, and failure modes:
./scripts/Sync-OpsInventory.ps1; "exit=$LASTEXITCODE"            # nothing to do

# someone creates a server by hand, outside the source of truth
$null = Invoke-OpsApi /api/secure/servers -Method Post -RetryNonIdempotent `
    -Body @{ Name = 'web-09'; Env = 'prod'; Region = 'canadacentral'; IP = '10.30.1.99'; Monitored = $false }
./scripts/Sync-OpsInventory.ps1; "exit=$LASTEXITCODE"

./scripts/Sync-OpsInventory.ps1 -MaxRetries 0; "exit=$LASTEXITCODE"   # faults are no longer absorbed
$env:OPSKIT_API_TOKEN = 'wrong'
./scripts/Sync-OpsInventory.ps1; "exit=$LASTEXITCODE"
$env:OPSKIT_API_TOKEN = 'lab-token-7f3a'
exit=0

WARNING: 1 item(s) not in sync: prod/web-09
Key         Action    Result Detail
---         ------    ------ ------
prod/web-09 Unmanaged Review only in API

exit=1
Write-Error: Sync aborted, API not readable: GET http://127.0.0.1:5050/api/secure/servers?page=2&pageSize=5 failed after 1 attempt(s): HTTP 429 Injected rate limit.
exit=2
Write-Error: Sync aborted, API not readable: GET http://127.0.0.1:5050/api/secure/servers?pageSize=5 failed after 1 attempt(s): HTTP 401 Missing or invalid bearer token.
exit=2
4. Run it the way a scheduler would, and read the report:
pwsh -NoProfile -NonInteractive -File ./scripts/Sync-OpsInventory.ps1 | Out-Null; "exit=$LASTEXITCODE"
$r = Get-Content ./tmp/sync-report.json -Raw | ConvertFrom-Json
$r.Changes
$r.Results | Group-Object Result -NoElement
Invoke-RestMethod http://127.0.0.1:5050/stats
exit=1
1

Count Name
----- ----
   12 InSync
    1 Review

requests : 30
e401     : 1
e429     : 4
e503     : 5
secure   : 28

The child pwsh inherited OPSKIT_API_TOKEN from the environment — the CI pattern. Exit 1 is correct: prod/web-09 still needs a human decision. Nine injected faults hit the client in this session; every one was either retried or reported with exit 2.

Cleanup:
Invoke-RestMethod http://127.0.0.1:5050/shutdown -Method Post
$api | Wait-Job -Timeout 5 | Remove-Job
Remove-Item Env:OPSKIT_API_TOKEN
Remove-Item ./tmp/sync-report.json
Acceptance criteria

Open-ended self-check

1. Why does the script read both sides completely before changing anything?

So that a read failure (exit 2) never leaves a half-applied sync, and so that the plan (and the -WhatIf output) is complete and reviewable. It also avoids interleaving reads and writes against a paginated list that the writes would shift.

2. The API starts returning 200 with an empty list during an incident. What happens, and how would you protect against it?

Every local server would be planned as Create — the API would answer 409 for each, the results would be Failed, exit 1. With a delete-capable sync it would be far worse. Protect with a sanity threshold: abort with exit 2 if the remote count is below, say, 50% of the local count or of the previous report.

3. How would you run this nightly against a real API from GitHub Actions?

A scheduled workflow, shell: pwsh, OpsKit installed from your feed (Lesson 4), OPSKIT_API_URL as a variable and OPSKIT_API_TOKEN from an environment secret (or a federated token exchange). Run -WhatIf nightly and upload the JSON report as an artifact; run apply mode only on a protected environment with approval. Exit 1 opens an issue, exit 2 pages on-call.

4. Which parts of today's lesson would change if the inventory lived in Azure instead of the mock API?

The Api source becomes Resource Graph (read) plus Update-AzTag / New-Az… (write) with -WhatIf; authentication becomes managed identity or OIDC with an explicit Set-AzContext guard; retries for ARM are handled by Az, but throttling still argues for one Resource Graph query instead of many calls. The plan / ShouldProcess / report / exit-code structure stays the same.

Sources and version notes

Version facts were checked on 2026-11-24 against Microsoft Learn, AWS documentation, module metadata and YouTube oEmbed; command outputs were produced on PowerShell 7.6.10 against a local mock API
Verification date 2026-11-24
TopicVerified resultSources (accessed 2026-11-24)
Web cmdlets on 7.6Parameter lists of Invoke-RestMethod/Invoke-WebRequest read on 7.6.10: -ConnectionTimeoutSeconds (alias -TimeoutSec), -OperationTimeoutSeconds, -MaximumRetryCount, -RetryIntervalSec, -FollowRelLink, -SkipHttpErrorCheck, -StatusCodeVariable, -ResponseHeadersVariable, -UnixSocket. The 7.4 docs already list the timeout parametersInvoke-RestMethod; Invoke-WebRequest; this lesson's runs
HTTP error behavior4xx/5xx → HttpResponseException, statement-terminating; -ErrorAction SilentlyContinue/Ignore do not hide it; ErrorDetails.Message holds the (pretty-printed) JSON body; -StatusCodeVariable stays empty when the call throwsThis lesson's runs (Module 1)
Built-in retryRetries 404 and POST, honors Retry-After on 429 (waited 3 s instead of 1 s), does not retry timeouts or refused connections; -OperationTimeoutSeconds 1 did not cut a 3-second time-to-first-byteThis lesson's runs (Module 2); RFC 9110 Retry-After
ConvertTo-JsonDefault depth 2; truncation warning; ConvertFrom-Json -AsHashtable returns OrderedHashtable on 7.6ConvertTo-Json; runs
SecretsSecretManagement 1.1.2 and SecretStore 1.0.6 command lists, syntax and enum values (Authenticate: None, Password; Interaction: None, Prompt; Scope: CurrentUser, AllUsers) read from the modules saved to a scratch folder; PSReadLine 2.4.5 history handler decisions reproducedSecretManagement; SecretStore; Secrets in automation
Az PowerShellAz 16.0.0 roll-up (102 modules in its manifest), Az.Accounts 5.5.0 parameter sets of Connect-AzAccount, ShouldProcess/ConfirmImpact of Az.Resources 10.0.0 / Az.Compute 11.6.0 cmdlets, Search-AzGraph (Az.ResourceGraph 1.3.0): -First 1–1000, response type PSResourceGraphResponse with SkipToken and Data — all read from installed module metadataInstall; Connect-AzAccount; Context persistence; Search-AzGraph; Resource Graph
OIDC / managed identityFederated credentials for GitHub Actions; non-interactive sign-in optionsGitHub Actions → Azure with OIDC; Non-interactive sign-in
AWS.ToolsAWS.Tools 5.0.344 / Installer 2.0.6 metadata (EC2 843 commands, S3 112, Get-EC2Instance output Reservation, -Select help text, Get-AWSRegion 45 regions, auto-iteration mode standard); V5 changes (auto-iteration, nullable types, -PassThru removed, credential env vars, error text) and the credential search order from AWS docsGet started; Migrating to V5; Credential resolution; Regions
Preference propagationA script's -WhatIf/-Verbose did not reach a module function (change performed) but reached a script-defined function — reproduced on 7.6.10about_Preference_Variables; runs (Module 6)
ThrottlingARM request limits and 429 handlingARM throttling
Mock API and OpsKitStart-MockApi.ps1, Set-LabServerTag, OpsKit v0.5 and Sync-OpsInventory.ps1 exactly as printed, run on 7.6.10 (Windows, thread job, 127.0.0.1:5050)This lesson's runs

Video verification notes

This lesson lists only videos whose titles and channels were checked via YouTube oEmbed (https://www.youtube.com/oembed?url=…&format=json) on 2026-11-24:

oEmbed only verifies titles and channels; the videos were not watched segment by segment, and the “meta” descriptions come from titles and public information. Several are older than PowerShell 7.6, Az 16 or AWS.Tools V5; where behavior differs, this lesson is authoritative. Two candidate videos found by search were rejected because oEmbed did not return metadata. No verified video was found for: the exact 7.x retry rules and timeout parameters, PSReadLine's history filter, preference propagation into modules, or building a retrying REST client module.

Voice narration notes

The “Voice” tab uses the browser's built-in Web Speech API to read the narration script (en-US); it needs no network access or external scripts. The courseware cannot embed MP3 files or generate video; the narration and storyboards can be passed to a TTS or video tool.

Known limitations

  • No cloud sign-in was performed. All outputs of Connect-AzAccount, Get-AzContext, Get-AzResourceGroup, Get-AzVM, New-/Remove-AzResourceGroup -WhatIf, Update-AzTag, Search-AzGraph query results, Get-STSCallerIdentity, Get-EC2Instance, Get-S3Bucket, AWS credential errors and the four-source Get-OpsCloudInventory run are Expected output with illustrative IDs, names and counts. Az/AWS cmdlet metadata (parameter sets, ShouldProcess, output types, help text, region list) is real.
  • SecretManagement vault operations were not run (no Register-SecretVault, Set-Secret, Set-SecretStoreConfiguration or Unlock-SecretStore on the lab machine, to avoid changing the user profile). Their outputs and the “no extension vaults registered” message are Expected; command lists, syntax and enum values are real.
  • The Azure CLI call shown (az version) is local; its line count depends on installed extensions.
  • Run environment: Windows 11, PowerShell 7.6.10, .NET 10.0.15; the mock API ran as a thread job. HttpListener on 127.0.0.1 worked without administrator rights on the lab machine; Linux and macOS were not tested. Paths were replaced with C:\Users\labadmin\….
  • Timings (2.0 s, 3.0 s, 3.7 s) are from one run on an idle machine; expect small differences. Where injected faults land in the integrated lab depends on the number of earlier requests.
  • Some error displays are shortened to the first line or to the error message (“error view shortened”).
  • The animations simplify: they omit TLS, proxies, redirects, HTTP/2 negotiation, jitter and the exact internals of MSAL and the AWS SDK credential providers.