PowerShell 第 7 课:云与 API 自动化——REST、Az、AWS.Tools 与机密
Get-OpsServer、Get-OpsConfig、Test-OpsEndpoint);第 4 课把它们打包成模块(v0.2);第 5 课加入错误处理、-WhatIf、重试和日志(v0.3,Invoke-OpsBackup);第 6 课实现并行与远程执行(v0.4,Invoke-OpsHealthCheck)。本课把同一套工具对准 HTTP API 和云。里程碑:OpsKit v0.5 新增 Invoke-OpsApi(持有者令牌来自 SecretManagement 或环境变量,只对瞬时故障重试,遵守 Retry-After,支持分页)和 Get-OpsCloudInventory(为本地清单、API、Azure 和 AWS 提供统一的对象模型)。第 8 课为它编写测试并发布为 v1.0。云平台基础请参见 Azure 和 AWS 课程。- 在
Invoke-RestMethod(正文 → 对象)与Invoke-WebRequest(状态、响应头、原始内容)之间做出选择;用ConvertTo-Json -Depth和-ContentType正确发送 JSON;用-StatusCodeVariable、-ResponseHeadersVariable和-SkipHttpErrorCheck读取状态码。 - 按 7.6 中 HTTP 错误的真实性质来处理它们:它们是语句终止性错误,
-ErrorAction SilentlyContinue无法隐藏;从$_.ErrorDetails.Message读取 API 返回的错误正文。 - 调用真实 API:用
-FollowRelLink或nextLink循环遍历分页;准确掌握-MaximumRetryCount会重试什么(所有 4xx/5xx,包括 404 和 POST,429 时遵守Retry-After——但不包括超时和连接被拒绝);区分-ConnectionTimeoutSeconds(别名-TimeoutSec)与-OperationTimeoutSeconds——本课的核心动画。 - 让机密远离代码、历史记录和日志:
-Authentication Bearer -Token <SecureString>、由 CI 注入的环境变量、SecretManagement + SecretStore,以及借助托管标识 / OIDC 联合凭据实现无令牌的 CI。 - 针对不同场景选择合适的方式登录 Azure(交互式、设备代码、托管标识、带证书的服务主体、联合令牌),用
Set-AzContext固定上下文,并执行只读查询。 - 只安装需要的 AWS.Tools 模块,以可预测的方式解析凭据和区域(配置文件、SSO、环境变量、角色),并整形
Get-EC2Instance的 Reservations → Instances 输出;了解 V5 的自动翻页和-Select。 - 让云变更幂等:查询 → 比较 → 设置、用标签表示归属、
SupportsShouldProcess包装函数、专门处理“未找到”,以及已验证的陷阱:脚本的-WhatIf不会传递到模块函数。 - 把嵌套的云端 JSON 整形成扁平报表(
-ExpandProperty、成员枚举、计算属性),用 KQL 查询 Azure Resource Graph,导出 CSV/JSON——并交付 OpsKit v0.5 以及一个带退出码、能扛住注入故障的清单同步脚本。
1 小时时间分配
| # | 时间 | 模块 | 核心内容 | 动画 / 交互 | 实验(~/pslab) |
|---|---|---|---|---|---|
| 0 | 课前 | 模拟 API 与账号 | Start-MockApi.ps1:运行在 127.0.0.1:5050 上的本地 HttpListener API(分页、503、429、慢响应、持有者令牌);可选的 Azure / AWS 沙盒;模块 | 自检清单 | 启动、探测并停止模拟 API |
| 1 | 00–06 | IRM 与 IWR | JSON → PSCustomObject、-Headers、-Body + ConvertTo-Json -Depth、-ContentType、-StatusCodeVariable、-SkipHttpErrorCheck、ErrorDetails | 请求 → 响应 → 对象 | GET、POST,以及用三种方式处理 404 |
| 2 | 06–13 | 真实 API | -FollowRelLink、nextLink 循环、-MaximumRetryCount / -RetryIntervalSec、429 + Retry-After、连接超时与操作超时 | 核心动画:一次分页并带重试的 API 调用 | 实测到底哪些会被重试 |
| 3 | 13–21 | 认证与机密 | 以 SecureString 形式使用持有者令牌、-AllowUnencryptedAuthentication、CI 中的环境变量、PSReadLine 历史过滤、SecretManagement / SecretStore、托管标识、OIDC | 令牌从哪里来? | 从环境变量读取令牌;检查历史记录会保存什么 |
| 4 | 21–28 | Az PowerShell | 模块化安装、Connect-AzAccount 参数集、上下文、Set-AzContext、Get-AzResourceGroup、Get-AzVM -Status、-WhatIf、Az 与 az 对比 | 登录方式 → 上下文 → 查询 | 离线查看 Az 元数据;可选的沙盒查询 |
| 5 | 28–35 | AWS.Tools | AWS.Tools.Installer、配置文件与 SSO、凭据解析、-Region / Set-DefaultAWSRegion、Get-EC2Instance、Get-S3Bucket、-Select、自动翻页 | 凭据与区域解析 | 把模块保存到文件夹;离线设置区域默认值 |
| 6 | 35–42 | 幂等变更 | 查询 → 比较 → 设置、标签、ShouldProcess 包装、“未找到”与真实错误、首选项变量传递到模块 | 先查后改的决策路径 | 对模拟 API 运行两次 Set-LabServerTag |
| 7 | 42–50 | 云数据 | 嵌套 JSON、-ExpandProperty、计算属性、Search-AzGraph + KQL、CSV/JSON 报表、零成本查询 | 从原始 JSON 到报表 | 把 EC2 和 Resource Graph 样例展平成 CSV |
| 8 | 50–60 | OpsKit v0.5 | Invoke-OpsApi(令牌、只重试瞬时故障、退避、分页、ShouldProcess)和 Get-OpsCloudInventory(Local / Api / Azure / Aws) | Invoke-OpsApi 流程 + 排错树 | 加入两个函数,升级到 0.5.0,对模拟 API 运行 |
| — | 课后 | 速查表 · 综合实验 | Sync-OpsInventory.ps1:针对存在漂移并注入 503/429 故障的模拟 API 做清单同步;退出码 0 / 1 / 2 | 结业测验(12 题) | 先收敛,再保持幂等 |
知识覆盖矩阵
| 目标技能 | M1 | M2 | M3 | M4 | M5 | M6 | M7 | M8 | 关键命令 | 实验 |
|---|---|---|---|---|---|---|---|---|---|---|
| 调用 REST API 并读取响应 | ✓ | ✓ | ✓ | · | · | ✓ | · | ✓ | Invoke-RestMethod、Invoke-WebRequest、-StatusCodeVariable | M1、M8 |
| 处理 HTTP 错误与错误正文 | ✓ | ✓ | ✓ | · | · | ✓ | · | ✓ | try/catch、$_.ErrorDetails.Message、-SkipHttpErrorCheck | M1、M6 |
| 分页、重试、限流、超时 | · | ✓ | · | · | ✓ | · | ✓ | ✓ | -FollowRelLink、-MaximumRetryCount、Retry-After、-ConnectionTimeoutSeconds | M2、综合实验 |
| 让机密远离代码和历史记录 | · | · | ✓ | ✓ | ✓ | · | · | ✓ | -Token、Get-Secret、$env:、OIDC | M3、M8 |
| 登录并固定云上下文 | · | · | ✓ | ✓ | ✓ | ✓ | · | · | Connect-AzAccount、Set-AzContext、Set-AWSCredential、-Region | M4、M5 |
| 幂等、可预演的变更 | · | · | · | ✓ | · | ✓ | · | ✓ | SupportsShouldProcess、-WhatIf、Update-AzTag -Operation Merge | M6、综合实验 |
| 把嵌套 JSON 整形成报表 | ✓ | ✓ | · | ✓ | ✓ | · | ✓ | ✓ | -ExpandProperty、@{n=;e=}、Search-AzGraph、Export-Csv | M7 |
| 封装进 OpsKit 并提供退出码 | · | · | · | · | · | ✓ | · | ✓ | Invoke-OpsApi、Get-OpsCloudInventory、exit 0/1/2 | M8、综合实验 |
本课不涉及的内容(以及去哪里学)
| 主题 | 为什么不在本课 | 去哪里学 |
|---|---|---|
| Azure 和 AWS 服务本身(网络、IAM / RBAC 设计、定价) | 本课是对它们做自动化,而不是讲解平台本身 | Azure 课程、AWS 课程 |
| Bicep / ARM 模板、CloudFormation、Terraform | 声明式基础设施属于另一类工具;本课中 PowerShell 用于查询、粘合和有针对性的变更 | Terraform 课程 |
| Microsoft Graph PowerShell SDK(Entra ID 用户、组、应用) | 模式相同(Connect-、上下文、分页),但它是一个庞大的独立 SDK | Microsoft Learn:Microsoft Graph PowerShell |
| OAuth 流程详解(授权码、PKCE、令牌刷新) | Az 和 AWS.Tools 会替你处理;本课直接使用现成的持有者令牌 | 身份提供方的文档 |
错误处理基础(终止性与非终止性错误、$ErrorActionPreference) | 默认已在第 5 课掌握;本课将其应用到 HTTP | 第 5 课 |
并行执行大量 API 调用(ForEach-Object -Parallel、线程作业) | 第 6 课已结合限流讲过;并行调用也会成倍增加 429 | 第 6 课 |
用 Pester 模拟 Invoke-RestMethod、OpsKit 的 CI 发布 | 属于测试与发布 | 第 8 课 |
如何使用本教材
原理 · 图解 · 动画 · 命令 · 实验 · 生产案例 · 排错 · 测验 · 语音 · 视频。在模块 1 之前启动模拟 API(模块 0)并保持运行;模块 1–3、6 和 8 中所有“实际输出”都来自它。模块 2 中分页并带重试的调用是贯穿本课的主线。
测验得分达到 70% 或以上,或点击“标记本模块为已完成”,都会计入进度。进度保存在本浏览器的本地存储中(如果浏览器禁用了本地存储,刷新后会重置)。
“语音”页面使用浏览器内置的 Web Speech API 朗读讲解稿。即使没有安装语音包,也可以直接阅读讲解稿,或把它交给 TTS 工具。
-ConnectionTimeoutSeconds / -OperationTimeoutSeconds 参数自 PowerShell 7.4 起提供;在 7.6 中 -TimeoutSec 是 -ConnectionTimeoutSeconds 的别名。模块 0 · 准备:本地模拟 API 与可选的云账号
Start-MockApi.ps1,这是一个约 190 行的 PowerShell 脚本,在 127.0.0.1 上提供 ~/pslab/data/inventory.json 的内容。云账号是可选的,只在 Azure / AWS 的“预期输出”部分才需要。- 第 1–6 课,尤其是:错误记录与
try/catch(第 5 课)、SupportsShouldProcess(第 3、5 课)、线程作业(第 6 课),以及~/pslab/OpsKit中的 OpsKit 模块(v0.4)。 - PowerShell 7.4 或更高版本(推荐 7.6)。
Start-ThreadJob来自随附的Microsoft.PowerShell.ThreadJob模块。 - 可选:一个 Azure 沙盒订阅,你在其中拥有 Reader 角色(模块 6 还需要对一个空资源组拥有 Contributor),和/或一个带只读角色的 AWS 沙盒账号。上课时绝不要使用生产订阅或生产账号。
热身:凭记忆回答(30 秒)
1. 第 5 课中,非终止性错误和语句终止性错误有什么区别?不加 -ErrorAction Stop 时,try/catch 能捕获哪一种?
非终止性错误(Write-Error、大多数 cmdlet 的“项目未找到”错误)会写入错误流,命令继续执行;只有加上 -ErrorAction Stop,try/catch 才能看到它。语句终止性错误(.NET 异常、$PSCmdlet.ThrowTerminatingError())会终止当前语句,并且总能被捕获。模块 1 会证明 Invoke-RestMethod 返回的 HTTP 错误响应属于后者。
2. 在线程作业或 ForEach-Object -Parallel 中,$using: 起什么作用(第 6 课)?
它把调用方作用域中的值复制到另一个运行空间。今天的模拟 API 运行在线程作业中,因此它与你共享进程,但不共享你的变量。
3. SupportsShouldProcess 给函数带来了什么?决策在哪里发生?
带来 -WhatIf 和 -Confirm;决策发生在 $PSCmdlet.ShouldProcess(target, action) 中。模块 6 会补充一条关于从脚本调用模块函数的重要规则。
步骤 1:保存 Start-MockApi.ps1
把下面的脚本保存为 ~/pslab/Start-MockApi.ps1。它只用到 System.Net.HttpListener(.NET 的一部分,可在 Windows、Linux 和 macOS 上运行),只监听 127.0.0.1,所有状态都保存在内存中,并且一次只处理一个请求——因此一次 /slow 调用会拖慢下一个请求,这也提醒你真实服务器同样会排队。在 Windows 上,非管理员可以在不配置 URL ACL 的情况下监听 http://127.0.0.1:<port>/(已在实验机上验证);如果你的策略不同,请修改 -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.'
| 端点 | 行为 | 用于 |
|---|---|---|
GET /api/servers?env=&page=&pageSize= | 返回一页(默认 5 项)+ 正文中的 nextLink + Link: <…>; rel="next" 响应头 | M1、M2 |
GET /api/servers/{env}/{name} | 返回一台服务器;不存在时返回 404 和 {"error":{"code":"NotFound",…}} | M1、M2、M8 |
POST /api/servers | 以 201 回显请求内容并附带 Location 响应头;缺少 Name 时返回 400;正文不是 JSON 时返回 500 | M1 |
GET|PUT /api/servers/{env}/{name}/tags | 标签保存在内存中 | M6 |
/flaky?key=&fail=2 · /ratelimit?key=&after=2 · /slow?sec=5 | 每个 key 先返回 fail 次 503,然后 200 · 每个 key 返回一次 429 + Retry-After · 延迟后返回 200 | M2、M8 |
/api/secure/servers(GET、POST)· /api/secure/servers/{env}/{name}(PUT) | 需要 Authorization: Bearer lab-token-7f3a;否则返回 401 + WWW-Authenticate。-FailEvery N 让每第 N 次调用注入 503/429;-Drift 会删除 prod/bastion-01 并修改 dev/db-01 的 IP | M3、M8、综合实验 |
步骤 2:启动、探测、停止
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
线程作业运行在你的 pwsh 进程内:关闭终端就会停止 API。在本课余下部分请保留 $api。在同一端口上再启动一份副本会立即失败:
$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
用完后干净地停止它(每当某个模块要求时,再用第一段代码重新启动):
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)
步骤 3:本课所需模块
| 需求 | 安装(在你自己的机器上) | 说明 |
|---|---|---|
| 使用模拟 API 的模块 1–3、6–8 无需额外安装 | — | Invoke-RestMethod、ConvertFrom-Json、线程作业和 PSReadLine 都随 PowerShell 7.6 提供 |
| SecretManagement + SecretStore(M3、M8) | Install-PSResource Microsoft.PowerShell.SecretManagement, Microsoft.PowerShell.SecretStore -Scope CurrentUser | 可选;OpsKit 会回退到 $env:OPSKIT_API_TOKEN |
| Az(M4、M6、M7) | Install-PSResource Az.Accounts, Az.Resources, Az.Compute, Az.ResourceGraph -Scope CurrentUser | 只安装需要的服务模块;Az 16.0.0 汇总模块的清单中列出了 102 个模块 |
| AWS.Tools(M5) | Install-PSResource AWS.Tools.Installer -Scope CurrentUser,然后 Install-AWSToolsModule EC2, S3, SecurityToken -Cleanup | 安装器让所有 AWS.Tools 模块保持同一版本 |
只是看看?如果想阅读命令和帮助而不安装到你的用户配置中,可以把模块保存到一个文件夹,并只在当前会话中把它加入 $env:PSModulePath——本课中的元数据就是这样得到的:
$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 # 仅当前会话 Get-Module -ListAvailable AWS.Tools.* | Format-Table Name, Version
Name Version ---- ------- AWS.Tools.Common 5.0.344 AWS.Tools.EC2 5.0.344
步骤 4(可选):云沙盒
- Azure:一个允许你做实验的订阅;创建一个空资源组
rg-pslab-h7,带标签owner=<you>。模块 4 和 7 只需要订阅上的 Reader;模块 6 需要对该资源组的 Contributor。本课中的每条命令要么是只读的,要么先以-WhatIf形式展示。 - AWS:一个账号,带有允许
ec2:DescribeInstances和s3:ListAllMyBuckets的 SSO 权限集或角色。用 AWS CLI(aws configure sso)配置;模块 5 会读取该配置文件。 - 费用:本课所有查询都是免费的(Resource Graph、Describe*、List*)。这里不会创建任何计费资源。
环境自检清单
POST /shutdown、Stop-Job 或关闭 pwsh 来停止。它的令牌 lab-token-7f3a 只是实验用值——任何真实场景都不要沿用硬编码令牌的做法(模块 3)。在云上:使用沙盒,先读后写,每个变更都先用 -WhatIf 运行,并给你创建的资源打标签。实验文件放在 ~/pslab/tmp;随时可以删除。模块 1 · Invoke-RestMethod 与 Invoke-WebRequest:JSON 转对象、请求头与状态码
- 预测
Invoke-RestMethod的输出类型(JSON 得到 PSCustomObject,XML 得到 XmlDocument,其他为字符串)以及Invoke-WebRequest的输出类型(带StatusCode、Headers、Content的BasicHtmlWebResponseObject)。 - 正确发送 JSON 请求体:
ConvertTo-Json -Depth+-ContentType 'application/json';知道把哈希表传给-Body时会发生什么。 - 用
-StatusCodeVariable和-ResponseHeadersVariable捕获成功调用的状态码与响应头。 - 处理 4xx/5xx:对
HttpResponseException使用try/catch,从$_.ErrorDetails.Message读取 API 的错误正文,或用-SkipHttpErrorCheck把错误正文当作普通结果返回。
What:两个 cmdlet,一套 HTTP 栈
Invoke-RestMethod(别名 irm) | Invoke-WebRequest(别名 iwr) | |
|---|---|---|
| 返回 | 转换后的正文:JSON → PSCustomObject(数组会被逐个枚举),XML/RSS → XmlDocument/条目,其他 → 字符串 | 一个 BasicHtmlWebResponseObject:StatusCode、StatusDescription、Headers(值为 String[])、Content(字符串)、RawContentLength、Links、Images |
| 状态码与响应头 | 只能通过 -StatusCodeVariable 和 -ResponseHeadersVariable 获取 | 始终在结果对象上 |
| 分页辅助 | -FollowRelLink / -MaximumFollowRelLink(模块 2) | — |
| 典型用途 | JSON API:你要的是数据 | 下载(-OutFile)、健康检查、调试响应头、非 JSON 内容 |
两者共享所有请求参数:-Method、-Headers、-Body、-ContentType、-Authentication/-Token、-MaximumRetryCount、超时、代理、证书、-SkipHttpErrorCheck。在 PowerShell 7 中二者都不再依赖 Internet Explorer;-UseBasicParsing 仍被接受但会被忽略。
Why:类型在 JSON 中得以保留,在 CSV 中不会
第 2 课说明过 Import-Csv 会把一切变成字符串。JSON 保留类型:模拟 API 的 Monitored 到达时是 Boolean,Port 是 Int64(下文已验证),所以 Where-Object Monitored 直接可用。代价是:发出请求时嵌套对象需要 -Depth(ConvertTo-Json 默认深度为 2,超出部分会被截断,只给出一条警告)。
How:请求体规则
-Body 的值 | 实际发送的内容 | 对模拟 API 的验证结果 |
|---|---|---|
($obj | ConvertTo-Json -Depth 10) + -ContentType 'application/json' | JSON 文本 | 201 Created ✓ |
-Method Post 配合一个哈希表 | application/x-www-form-urlencoded 表单数据(Name=x&Env=dev) | 500 —— API 无法解析 JSON ✗ |
-Method Get 配合一个哈希表 | 查询字符串参数 | 适合 ?env=prod&pageSize=5 |
不带 -ContentType 的字符串 | POST 时以 application/x-www-form-urlencoded 发送 | 许多 API 会以 415 拒绝 |
When:错误 —— 以及为什么 -ErrorAction 帮不上忙
对于 4xx/5xx 响应,PowerShell 7 会抛出 Microsoft.PowerShell.Commands.HttpResponseException,这是一个语句终止性错误。已在 7.6.10 上验证:-ErrorAction SilentlyContinue 和 -ErrorAction Ignore 仍然会打印错误,并把 $? 置为 False。你有三种选择:
try { … } catch { … }—— 读取$_.Exception.Response.StatusCode(一个HttpResponseMessage),以及$_.ErrorDetails.Message中 API 的错误正文(PowerShell 会把 JSON 正文格式化输出)。-SkipHttpErrorCheck -StatusCodeVariable code—— 完全不产生错误;错误正文作为普通输出返回,$code告诉你发生了什么。最适合封装函数(OpsKit 在模块 8 中使用它)。Invoke-WebRequest -SkipHttpErrorCheck,然后根据.StatusCode分支处理。
-Body @{…} 发送的是 JSON” —— 它发送的是表单数据;请用 ConvertTo-Json 转换。② “ConvertTo-Json 会序列化一切” —— 默认深度是 2;更深的层级会变成 System.Collections.Hashtable 之类的字符串,只给一条警告。③ “-ErrorAction SilentlyContinue 能屏蔽 404” —— 对 HTTP 错误无效;请用 try/catch 或 -SkipHttpErrorCheck。④ “调用失败时 -StatusCodeVariable 也会被赋值” —— 已验证:抛出错误时它保持为空;它要配合 -SkipHttpErrorCheck 才有用。⑤ “响应头的值是字符串” —— 在 7.x 中每个响应头的值都是 String[]。请求与响应:每个 cmdlet 交给你什么
ConvertTo-Json 深度:丢失了什么
请求 → 响应 → 对象
选择一次调用,然后逐步查看 PowerShell 发送了什么、模拟 API 返回了什么,以及最终你的变量里是什么。
WebRequestPSCmdlet。它构建一个 HttpRequestMessage,通过 HttpClient 发送,并检查 IsSuccessStatusCode。失败时(且未使用 -SkipHttpErrorCheck)它把正文读入 ErrorDetails 并调用 ThrowTerminatingError —— 这就是 -ErrorAction 无法让它静默的原因。成功时,Invoke-RestMethod 查看 Content-Type,并用与 ConvertFrom-Json 相同的代码转换 JSON。命令表
| 命令 / 参数 | 用途 | 说明 |
|---|---|---|
Invoke-RestMethod $uri | GET 并转换正文 | JSON 数组会被枚举到管道中 |
Invoke-WebRequest $uri | 完整响应 | .StatusCode、.Headers['Content-Type']、.Content |
-Method Post|Put|Patch|Delete | HTTP 方法 | 其他方法用 -CustomMethod |
-Headers @{ 'X-Api-Version' = '2026-01' } | 请求头 | 认证请用 -Authentication/-Token(模块 3) |
-Body ($o | ConvertTo-Json -Depth 10) -ContentType 'application/json' | JSON 请求体 | 绝不要依赖默认深度 2 |
-StatusCodeVariable sc -ResponseHeadersVariable h | 从 irm 获取状态码与响应头 | 变量名不带 $ |
-SkipHttpErrorCheck | 把 4xx/5xx 当作普通输出 | 与 -StatusCodeVariable 搭配 |
$_.ErrorDetails.Message | catch 中的 API 错误正文 | | ConvertFrom-Json 以读取 error.code |
$_.Exception.Response | catch 中的 HttpResponseMessage | .StatusCode、.Headers.RetryAfter、.ReasonPhrase |
-OutFile path [-Resume] | 下载到文件 | 加 -PassThru 可同时得到结果 |
GET:JSON 变成带类型的对象
$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
同一个调用改用 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
分页列表:外层信封与条目
$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
大多数云 API 会把列表包在一个信封里:Azure 用 value + nextLink,Microsoft Graph 用 value + @odata.nextLink,AWS 用 NextToken。始终要问:“条目在哪里,下一页在哪里?”(模块 2)。
POST:深度、内容类型、状态码与响应头
$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 # 默认 -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
哈希表请求体陷阱
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.
服务器收到的是 Env=dev&Name=x(表单编码),它的 JSON 解析器失败了。真实 API 会返回 400 或 415;道理是一样的。
一个 404,三种处理方式
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
如何验证:调用失败后,$Error[0].Exception.GetType().Name 为 HttpResponseException;-ErrorAction Ignore 的表现相同(同样已验证)。常见错误:给调用加上 -ErrorAction SilentlyContinue,再用 if (-not $result) 判断 —— 错误仍然会进入日志、CI 仍会把这一步标红,而你的脚本却以为是“未找到”。生产用途:在库代码中使用 -SkipHttpErrorCheck + -StatusCodeVariable,把每一类状态码都变成明确的决策(模块 8);在脚本中使用 try/catch 并记录 ErrorDetails.Message,它通常包含服务商的错误码和请求 ID。
目标:对模拟 API 执行读取、创建和失败请求,并解释每个结果。环境:pwsh 7.4+,模块 0 中的模拟 API。费用:无;没有任何流量离开 127.0.0.1。
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
$prod = (Invoke-RestMethod "$base/api/servers?env=prod&pageSize=50").value @($prod | Where-Object Monitored).Count
4
对 servers.csv 你需要写 -eq 'true'(第 1 课模块 6);JSON 直接给出真正的布尔值。
Content-Length 响应头和解析出的 IP。
$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
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
-Depth 的嵌套请求体,看看到达的是什么(模拟 API 会回显请求体)。
$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
案例 1:标签悄悄变成了 “System.Collections.Hashtable”
问题:一条通过 REST API 创建资源的流水线会写入成本中心标签。几周后财务发现上千个资源被打上了 "split": "System.Collections.Hashtable" 标签。根因:请求体由 ConvertTo-Json 构建却没有 -Depth;截断警告进入了 CI 系统不显示的警告流。修复:始终传入 -Depth(在 7.x 中可在脚本里设置 $PSDefaultParameterValues['ConvertTo-Json:Depth'] = 10);增加一个测试,对请求体做往返转换(ConvertTo-Json | ConvertFrom-Json)并比较一个深层的值。
案例 2:“未找到”逻辑顺带吞掉了 401
问题:一个清理脚本这样检查:$x = Invoke-RestMethod $uri -ErrorAction SilentlyContinue; if (-not $x) { create }。令牌过期后,每次检查都“什么也没找到”,脚本试图重新创建 200 个资源(全部失败,并发出 200 封错误邮件)。根因:把所有失败都当作“不存在”。修复:按状态码分支:404 → 不存在,401/403 → 停止本次运行,429/5xx → 重试(模块 2)。-SkipHttpErrorCheck -StatusCodeVariable 让这一点变得明确。
案例 3:一个“永远匹配不上”的响应头值
问题:if ($r.Headers['Content-Type'] -eq 'application/json') 总是为假。根因:在 PowerShell 7 中响应头的值是 String[],而且实际值是 application/json; charset=utf-8;对数组使用 -eq 是在过滤而不是比较。修复:$r.Headers['Content-Type'][0] -like 'application/json*'。
常见错误与修复
Response status code does not indicate success: 400 (Bad Request) / 415 (Unsupported Media Type)
原因:请求体不是 JSON(哈希表,或未带 -ContentType 的字符串),或因深度截断而缺少某个属性。
$json = $body | ConvertTo-Json -Depth 10 $json # 发送前先看一眼 Invoke-RestMethod $uri -Method Post -Body $json -ContentType 'application/json'
修复:打印 $_.ErrorDetails.Message;API 通常会指出是哪个字段有问题。
我已经用了 -ErrorAction SilentlyContinue,错误仍然显示
原因:在 PowerShell 7 中 HTTP 错误是语句终止性错误。
try { Invoke-RestMethod $uri } catch { if ($_.Exception.Response.StatusCode -eq 'NotFound') { $null } else { throw } }输出是字符串而不是对象
原因:服务器没有发送 Content-Type: application/json,因此 Invoke-RestMethod 返回了文本。
(Invoke-WebRequest $uri).Headers['Content-Type'] Invoke-RestMethod $uri | ConvertFrom-Json
Invoke-WebRequest 在脚本中显示进度条且很慢
原因:大文件下载时的进度渲染(在 7.x 中比 5.1 快得多,但在 CI 中仍是噪音)。
$ProgressPreference = 'SilentlyContinue'
'irm' 在这里能用,但我的脚本在另一台机器上失败
原因:脚本中使用了别名;在 PowerShell 7 中 curl 和 wget 不再是别名(会运行原生工具)。
修复:脚本中使用完整名称:Invoke-RestMethod、Invoke-WebRequest。
1. 只用 Invoke-RestMethod,获取一次 GET 的状态码和 X-Request-Id 响应头。
$null = Invoke-RestMethod "$base/health" -StatusCodeVariable sc -ResponseHeadersVariable h "$sc $($h['X-Request-Id'][0])"
2. 把 @{ Name='web-04'; Env='dev'; Meta=@{ a=@{ b=@{ c=1 } } } } 作为 JSON 发送,使 c 得以保留,并通过回显证明这一点。
$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同事的脚本在 CI 中打印了 “HTTP 404”,但作业是绿色的,下一步却因 “null-valued expression” 失败。发生了什么?你会怎么改?
脚本调用 Invoke-RestMethod 时没有处理错误;该语句失败,脚本继续执行(没有设置 $ErrorActionPreference = 'Stop'),作业的退出码来自最后一条命令。变量保持为 $null。修改:明确做出决策 —— 用 -SkipHttpErrorCheck -StatusCodeVariable 配合 switch,或用 try/catch 并重新抛出非 404 错误 —— 并让脚本在出现意外状态时 exit 1(或 throw),这样 CI 会在真正的原因处变红。
已验证的教学视频
官方文档
视频分镜(约 90 秒)
本教材无法直接生成视频或 MP3;分镜与旁白可交给视频工具使用。
画面:一个请求箭头,响应分成两个盒子:“IRM → 对象”、“IWR → 状态码、响应头、内容”。
旁白:同一个请求,不同的包装方式。
画面:一个嵌套哈希表;第 3 层变成文本 System.Collections.Hashtable,旁边一个小小的黄色警告。
旁白:发送 JSON 时一定要指定深度。
画面:一个 404 冲破了一把写着 “SilentlyContinue” 的伞。
旁白:HTTP 错误是终止性错误。要么捕获它,要么跳过检查并读取状态码。
画面:switch 语句:200 → 数据,404 → null,其他 → throw。
旁白:把每个状态码都变成一个决策。
模块 2 · 真实 API:分页、重试、限流与超时
- 用
-FollowRelLink(RFC 8288Link响应头)或nextLink/NextToken循环取回所有页,并用-MaximumFollowRelLink限制页数。 - 说清
-MaximumRetryCount/-RetryIntervalSec在 7.6 上会重试什么:所有 4xx/5xx 状态(包括 404,POST 也会重试),429 时遵循Retry-After—— 但不重试超时或连接被拒绝。 - 有意识地处理 429:读取
Retry-After、退避、降低并发。 - 在
-ConnectionTimeoutSeconds(别名-TimeoutSec,等待响应的整个时间)与-OperationTimeoutSeconds(读取响应流时的停顿)之间做出选择。
What:API 客户端必须面对的三个事实
| 事实 | API 如何表达 | 客户端的职责 |
|---|---|---|
| 列表是分页的 | Link: <url>; rel="next" 响应头(GitHub、模拟 API),正文中的 nextLink / @odata.nextLink(Azure、Graph),NextToken / ContinuationToken(AWS),$skipToken(Resource Graph) | 循环直到令牌为空;绝不假设第 1 页就是全部 |
| 失败往往是瞬时的 | 408、500、502、503、504;连接中断 | 以递增的等待时间重试几次;除非 API 支持幂等键,否则只对幂等请求重试 |
| 你一定会被限流 | 429 Too Many Requests(有时是 503)+ Retry-After: <seconds or HTTP date>;Azure Resource Manager 和 AWS 还会返回剩余配额响应头 | 至少等待 Retry-After 指定的时间;整体放慢速度 |
Why:内置重试的实测行为(7.6.10)
情形(-MaximumRetryCount 3 -RetryIntervalSec 1) | 是否重试? | 证据见下文 |
|---|---|---|
| 两次 503,然后 200 | 是 —— 第 3 次尝试成功,耗时 2.1 秒 | 命令,第 4 段 |
| 404(永久性) | 是 —— 3 次尝试,白白浪费 2.0 秒 | 第 5 段 |
429 且 Retry-After: 3 | 是 —— 等待了 3 秒而不是 1 秒:“Retrying after interval of 3 seconds” | 第 6 段 |
| 对返回 503 的端点执行 POST | 是 —— 一个非幂等请求被发送了 3 次 | 第 11 段 |
超时(达到 -TimeoutSec) | 否 —— 立即以 ConnectionTimeoutReached 失败(使用 -MaximumRetryCount 2 时:只尝试一次,1.0 秒) | 第 8 段;动画“timeout” |
| 连接被拒绝 / DNS 失败 | 否 | 第 10 段 |
所以内置重试同时过于积极(404、POST)又覆盖太窄(不处理网络错误)。对一次快速的 GET 来说没问题;库代码应自行对状态码分类 —— 这正是 OpsKit 的 Invoke-OpsApi 在模块 8 中所做的。
How:退避
等待 base × 2^(attempt−1)(0.5、1、2、4 秒……),设上限;当许多客户端同时重试时加入抖动(避免它们同步地冲击服务器);并让 Retry-After 覆盖计算出的延迟。尝试少量次数后停止,失败消息中要包含 URL、最后一次状态码和尝试次数。
When:用哪个超时?
| 参数 | 含义(已验证) | 适用于 |
|---|---|---|
-ConnectionTimeoutSeconds / -TimeoutSec | 设置 HttpClient.Timeout:连接 + 发送 + 等待响应头。服务器休眠 4 秒时,2 秒的限制会以 ConnectionTimeoutReached 失败 | 自动化中的每一次调用(默认值为 100 秒) |
-OperationTimeoutSeconds | 限制读取响应流时两次读取之间的时间。一个等待 3 秒才应答的服务器没有被 1 秒的操作超时切断 | 可能中途停滞的大文件下载和流式响应 |
-MaximumRetryCount 只重试瞬时错误” —— 它重试所有 4xx/5xx,包括 404 和 POST。② “它也会重试网络故障” —— 连接被拒绝和超时都不会被重试。③ “-FollowRelLink 返回一个扁平列表” —— 它每页返回一个结果;用 .value(成员枚举)来展平。④ “-OperationTimeoutSeconds 限制整个调用” —— 它不限制等待首字节的时间。⑤ “重试得越快恢复得越快” —— 面对 429,这只会让限流持续更久。时序图:一次分页并带重试的调用
决策:重试还是不重试?
核心动画:一次分页并带重试的 API 调用
每个场景都来自“命令”选项卡或模块 8 中的真实运行。观察客户端进行了哪些尝试、等待了多久、在哪里停止。
WebRequestPSCmdlet 中,重试循环包裹着发送操作:如果状态码不是成功且仍有剩余重试次数,它会等待 RetryIntervalSec —— 对于带 Retry-After 时长的 429,则等待该值 —— 向详细流写入 “Retrying after interval of N seconds”,然后再次发送请求。HttpClient 抛出的异常(超时、套接字错误)会立即跳出循环。-FollowRelLink 是外层的第二个循环,在每个成功的页面之后解析 Link 响应头。命令表
| 命令 / 参数 | 用途 | 说明(已在 7.6.10 上验证) |
|---|---|---|
-FollowRelLink [-MaximumFollowRelLink n] | 跟随 Link: rel="next" | 每页一个输出;n 计数包含第一页 |
while ($uri) { $r = irm $uri; $r.value; $uri = $r.nextLink } | 基于正文的分页 | Azure、Graph('@odata.nextLink')、模拟 API |
-MaximumRetryCount n -RetryIntervalSec s | 内置重试 | 所有 ≥ 400 的状态;429 遵循 Retry-After;异常不重试 |
$_.Exception.Response.Headers.RetryAfter | 在 catch 中读取 Retry-After | .Delta(TimeSpan)或 .Date |
-ResponseHeadersVariable h; $h['Retry-After'] | 同上,但不经过异常 | 配合 -SkipHttpErrorCheck |
-ConnectionTimeoutSeconds(别名 -TimeoutSec) | 等待响应的总时间 | 错误 ID 为 ConnectionTimeoutReached |
-OperationTimeoutSeconds | 读取正文时的停顿超时 | 不限制首字节到达时间 |
[Diagnostics.Stopwatch]::StartNew() | 测量实际发生了什么 | 比把代码块包进 Measure-Command 更轻量、更精确 |
1–2. 分页
$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 # 成员枚举把各页展平
$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 # 输出本页的条目
$uri = $resp.nextLink # 最后一页为 $null,循环结束
}
$all.Count
$all.Name -join ', '
6 web-01, web-02, api-01, edge-01, db-01, bastion-01
3–4. 瞬时 503:不使用与使用内置重试
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. 404 也会被重试
$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 与 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. 超时
$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 # 单线程的模拟 API 仍在处理 /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. 哪些不会被重试,哪些不应该被重试
$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
如何验证:模拟 API 的 /stats 统计服务器实际看到的请求 —— 客户端“只调用了几次”,服务器却收到了 5 次 503 和 2 次 429。常见错误:给一个会创建资源的 POST 加上 -MaximumRetryCount 5;如果服务器已经创建了条目却没能应答,你就会再创建一次。生产用途:脚本中的 GET 用 -MaximumRetryCount 3 -RetryIntervalSec 2 -TimeoutSec 30 是合理的默认值;在模块中则使用一个封装函数:只重试瞬时状态和网络错误、遵循 Retry-After,并且只在有幂等键或确认安全的 PUT 时才重试写操作。
目标:手工编写一个小的分页 + 重试循环,并与内置参数对比。环境:模拟 API 正在运行。费用:无。
$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
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)
Invoke-LabGet "$base/ratelimit?key=lab2&after=2";它应当耗时约 2 秒,而不是 0.5 秒。Invoke-RestMethod 中以 -TimeoutSec 1 调用 /slow?sec=3,观察异常绕过了你的状态码逻辑,然后加一个 try/catch,把 ConnectionTimeoutReached 视为瞬时故障。(之后等待 3 秒:模拟 API 是单线程的。)Remove-Item function:Invoke-LabGet;让 API 继续运行。案例 1:永远恰好有 1,000 台虚拟机的报表
问题:月度虚拟机报表每个月都显示 1,000 行,而实际规模一直在增长。根因:脚本只读取了 REST 列表的一页(以及 Resource Graph,其每次调用最多返回 1,000 行),忽略了 nextLink / $skipToken。修复:循环直到续页令牌为空;当 API 返回 count/totalRecords 时,增加一个断言比较行数。
案例 2:重试把限流变成了故障
问题:40 个并行的 Runbook 访问同一个 API;收到 429 后每个都每秒重试一次。API 的限流窗口不断延长,所有 Runbook 失败了 20 分钟。根因:固定的短重试间隔、忽略 Retry-After、没有全局并发限制。修复:遵循 Retry-After,带抖动的指数退避,并给并行循环加上 -ThrottleLimit(第 6 课)。7.x 的内置重试已经在 429 时遵循 Retry-After —— 这比许多手写循环都要好。
案例 3:网关超时后出现重复工单
问题:一个事件工具有时会开出两张完全相同的工单。根因:Invoke-RestMethod -Method Post -MaximumRetryCount 3;后端已经创建了工单,网关却返回了 504,重试又创建了第二张。修复:POST 不做自动重试,或发送 API 支持的幂等键请求头;需要重试时,先 GET 检查条目是否已存在(先查后改,模块 6)。
常见错误与修复
Response status code does not indicate success: 429 (Too Many Requests)
catch { $_.Exception.Response.Headers.RetryAfter } # Delta 或 Date
修复:至少等待这么久;降低并行度;错开调度时间(不要所有作业都在整点运行)。
The request was canceled due to the configured HttpClient.Timeout of N seconds elapsing
原因:达到了 -TimeoutSec/-ConnectionTimeoutSeconds(默认 100 秒)。修复:对已知较慢的端点调大超时,或使用异步 API(202 Accepted + 轮询状态 URL)。-MaximumRetryCount 不会重试这种情况。
我的循环永远不结束
原因:属性名写错(nextLink、'@odata.nextLink' 与 NextToken 混淆),或 API 返回空字符串而不是 null,导致 URL 重复。
$seen = @{}; while ($uri -and -not $seen[$uri]) { $seen[$uri] = 1; … }-FollowRelLink 只返回了第一页
原因:API 把下一页链接放在正文里,而不是 Link 响应头中。-FollowRelLink 只读取 rel="next" 响应头。修复:自己写循环。
重试让一次失败的调用耗时数分钟
原因:-MaximumRetryCount 重试了 401/403/404。修复:自行对状态码分类(-SkipHttpErrorCheck),或把内置次数设得很小。
1. 利用正文中的 nextLink、页大小为 2,把模拟 API 的所有 prod 服务器取回到一个数组中。
$u = "$base/api/servers?env=prod&pageSize=2"
$prod = while ($u) { $r = Invoke-RestMethod $u; $r.value; $u = $r.nextLink }
$prod.Count # 62. 不使用 try/catch,打印一个 429 的 Retry-After 值。
$null = Invoke-RestMethod "$base/ratelimit?key=q2" -SkipHttpErrorCheck -StatusCodeVariable sc -ResponseHeadersVariable h "$sc $($h['Retry-After'])"
一个 Azure Function 以 -MaximumRetryCount 5 -RetryIntervalSec 10 调用合作方的 API。当合作方的证书过期时,函数在 5 分钟后超时,而不是快速失败。请解释并修复。
TLS 失败是一种异常,它不会被重试 —— 所以这不是原因。更可能的是合作方返回了 4xx/5xx(例如其网关返回的 495/525 或 401),这会被重试 5 × 10 秒,而且每次尝试还可能等待到 -TimeoutSec(默认 100 秒)。修复:对状态码分类(只重试 408/429/5xx),设置较短的 -TimeoutSec,限制总耗时,并记录最后一次尝试的状态码和 ErrorDetails,让告警显示真正的原因。
已验证的教学视频
没有找到经过验证、讲解 -FollowRelLink、7.x 精确重试规则或 -OperationTimeoutSeconds 的视频;请以本模块的实测运行和官方文档为准。
官方文档
- Invoke-RestMethod(FollowRelLink、MaximumRetryCount、超时)
- RFC 9110:Retry-After · Azure Resource Manager 限流
视频分镜(约 90 秒)
本教材无法直接生成视频或 MP3;分镜与旁白可交给视频工具使用。
画面:三页依次滑入,“nextLink” 箭头把它们串起来,最后一个箭头为 null。
旁白:一页永远不是全部。跟着链接走,直到它为空。
画面:时序图:503 → 等待 → 200;429 → Retry-After 1 → 200。
旁白:重试瞬时故障,并让 Retry-After 决定等待多久。
画面:一张打勾的表格:404 被重试,POST 被重试,超时不重试。
旁白:内置重试同时过于积极又覆盖太窄。
画面:两块秒表:“首字节到达时间”与“读取中的停顿”。
旁白:TimeoutSec 限制等待响应的时间;OperationTimeoutSeconds 捕获停滞的数据流。
模块 3 · 认证与机密:令牌、SecretManagement 与 SecretStore
- 用
-Authentication Bearer -Token <SecureString>发送持有者令牌,并理解为什么不加-AllowUnencryptedAuthentication时 PowerShell 拒绝通过明文 HTTP 发送它。 - 清楚令牌可以存放在哪里:由 CI 注入的环境变量、SecretManagement 保管库、托管标识——以及绝不能出现在哪里:脚本文件、代码仓库、PSReadLine 历史记录、详细日志。
- 使用 SecretManagement API(
Get-Secret、Set-Secret、Get-SecretInfo、Register-SecretVault),并为交互式和无人值守两种场景配置 SecretStore 保管库。 - 解释托管标识和 GitHub Actions / Azure DevOps 的工作负载身份联合(OIDC),以及它们为何优于存储的客户端机密。
是什么:自动化脚本会遇到的几类凭据
| 凭据 | 有效期 | 示例 | 应当从哪里获取 |
|---|---|---|---|
| 持有者访问令牌 | 几分钟到几小时 | 用于 ARM 的 Entra ID 令牌(Get-AzAccessToken)、GitHub 令牌、模拟 API 的 lab-token-7f3a | 运行时从某个身份申请;从不存储 |
| API 密钥 / PAT / 客户端机密 | 数月 | SaaS API 密钥、服务主体机密 | 保管库(Key Vault、SecretStore、CI 机密存储)→ 环境变量或 Get-Secret |
| 证书 | 1–2 年 | 服务主体证书 | 证书存储 / Key Vault,通过指纹引用 |
| 托管标识 | 根本没有机密 | Azure VM、Function、Automation 账户;AWS 实例配置文件 / 任务角色 | 平台的元数据端点 |
| 联合(OIDC)令牌 | 几分钟,按作业发放 | GitHub Actions 的 id-token: write,换取 Azure 或 AWS 令牌 | CI 提供方,由云平台信任 |
为什么:PowerShell 中令牌泄露的三种已验证途径
| 泄露途径 | 已验证行为(7.6.10,PSReadLine 2.4.5) | 防护 |
|---|---|---|
| 命令历史文件 | PSReadLine 默认的历史处理器会把包含 token、password、asplaintext、secret、apikey 的行只保存在内存中——但 irm $u -Headers @{ Authorization = 'Bearer eyJ…' } 和 $env:OPSKIT_KEY = 'eyJ…' 被写入了历史文件 | 永远不要手敲机密;改为加载(Get-Secret、由 CI 设置的环境变量) |
| 明文 HTTP | 对 http:// 使用 -Authentication Bearer 会以 WebCmdletAllowUnencryptedAuthenticationRequiredException 失败 | 使用 HTTPS;只对环回地址允许例外(OpsKit 就是这样做的) |
| 输出与日志 | ConvertFrom-SecureString -AsPlainText 会打印令牌;SecureString 本身只打印类型名 | 令牌一直保持为 SecureString,直到最后一刻;绝不要 Write-Verbose 一个请求头 |
怎么做:一张图看懂 SecretManagement
Microsoft.PowerShell.SecretManagement 是一层抽象:一套 cmdlet(Get-Secret、Set-Secret、Get-SecretInfo、Remove-Secret)覆盖任意数量已注册的保管库扩展——Microsoft.PowerShell.SecretStore(本地加密文件,跨平台)、Az.KeyVault、KeePass、1Password、HashiCorp Vault,以及 Gallery 中的其他扩展。脚本调用 Get-Secret -Name OpsKitApiToken;由哪个保管库应答是配置问题,而不是代码问题。机密默认以 SecureString 返回(只有 API 确实需要字符串时才用 -AsPlainText)。
| SecretStore 设置(已验证的枚举值) | 取值 | 交互式笔记本 | 无人值守作业 |
|---|---|---|---|
-Authentication | None、Password | Password | Password,并从受保护的来源用 Unlock-SecretStore 解锁 |
-Interaction | None、Prompt | Prompt | None(提示会让作业挂起) |
-PasswordTimeout | 秒 | 900 | 足够覆盖一次运行 |
-Scope | CurrentUser、AllUsers | CurrentUser(存储按用户区分;服务账户有自己的存储) | |
何时用:按代码运行的位置来选
| 运行在 | 最佳选择 | 可以接受 | 避免 |
|---|---|---|---|
| 你的笔记本 | 交互式登录(Az/AWS SSO);API 密钥放 SecretStore | 为单个会话设置的环境变量 | 密钥写在 $PROFILE 里 |
| Azure VM、Function、Automation | 托管标识(Connect-AzAccount -Identity);第三方密钥放 Key Vault | 证书 | 应用设置中的客户端机密 |
| GitHub Actions / Azure DevOps | OIDC 联合(不存储任何云机密) | 仓库/环境机密 → 环境变量 | 在日志中回显机密、类似 set -x 的跟踪(Set-PSDebug -Trace) |
| AWS EC2 / ECS / Lambda | 实例配置文件 / 任务角色 | 跳板机上的 SSO 配置文件 | 服务器上 ~/.aws/credentials 中的访问密钥 |
-AllowUnencryptedAuthentication 无害”——这种习惯最终会带进生产;把它限定在环回地址。④ “SecretStore 是一台服务器”——它是按用户的加密文件。⑤ “放在 CI 机密存储中的服务主体机密和 OIDC 一样好”——它不会自行过期,在任何地方都能用;联合凭据则绑定到仓库、分支或环境。令牌从哪里来
SecretManagement 架构
令牌从哪里来?
逐步查看每种配置如何把凭据送进 API 调用,以及在哪里出问题。
-Authentication Bearer 时,Web cmdlet 只在构造 Authorization: Bearer … 头的那一刻才把 SecureString 转为文本;对非 HTTPS 的 URI,除非指定 -AllowUnencryptedAuthentication,否则拒绝这样做。PSReadLine 通过 AddToHistoryHandler 逐行决定:默认处理器在该行匹配敏感词模式时返回 MemoryOnly,否则返回 MemoryAndFile。托管标识和 OIDC 从不把长期机密放到磁盘上:平台按需签发短期令牌。命令表
| 命令 | 用途 | 说明 |
|---|---|---|
-Authentication Bearer -Token $ss | 发送持有者令牌 | -Token 是 [SecureString];字符串无法绑定 |
-AllowUnencryptedAuthentication | 允许通过 http 发送凭据 | 仅限环回实验环境 |
ConvertTo-SecureString $s -AsPlainText -Force | 包装收到的字符串(环境变量) | 只在边界处做一次 |
Get-Secret -Name n [-Vault v] [-AsPlainText] | 读取机密 | 默认返回 SecureString |
Set-Secret -Name n -Secret $v [-Metadata @{}] | 存储或更新 | -NoClobber 拒绝覆盖;支持 -WhatIf |
Get-SecretInfo [-Name *] | 列出名称、类型、元数据 | 从不返回值 |
Register-SecretVault -Name v -ModuleName Microsoft.PowerShell.SecretStore -DefaultVault | 添加保管库 | 按用户;每台机器一次 |
Set-SecretStoreConfiguration -Authentication Password -Interaction None -PasswordTimeout 3600 | 无人值守存储 | 之后用 Unlock-SecretStore -Password $p |
(Get-PSReadLineOption).AddToHistoryHandler | 历史过滤器 | 在键入之前先测试一行 |
1. 没有令牌,然后通过明文 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' # 在 CI 中它来自流水线的机密存储
$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. 对环回实验 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. SecureString 显示什么——以及如何绕过它
"$token" $token.Length ConvertFrom-SecureString $token -AsPlainText # 绝不要出现在会写日志的真实代码路径中
System.Security.SecureString 14 lab-token-7f3a
4. 这一行会被写入历史文件吗?
$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
最后一行没问题(其中没有机密)。带 JWT 的那两行 MemoryAndFile 会以明文留在该文件中。如果已经发生:先轮换令牌,再从文件中删除该行。
5. SecretManagement 与 SecretStore:命令(元数据来自真实模块)
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. 注册一个 SecretStore 保管库并使用它(在你自己的机器上)
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. 无人值守的 SecretStore(计划任务 / 服务账户)
# 以服务账户身份一次性设置。存储密码本身必须来自受保护的来源
# (Windows 上用 Export-Clixml 生成的 DPAPI 保护文件、Key Vault、CI 机密存储)——而不是来自脚本。
$storePw = Import-Clixml -Path C:\jobs\secrets\storepw.xml # SecureString,仅此账户在此机器上可读
Set-SecretStoreConfiguration -Scope CurrentUser -Authentication Password -Interaction None `
-PasswordTimeout 3600 -Password $storePw -Confirm:$false
# 每次运行:
Unlock-SecretStore -Password $storePw
$token = Get-Secret -Name OpsKitApiToken
(成功时无输出;Get-Secret 返回 SecureString)
8. CI:来自机密存储的环境变量,或者干脆没有机密
# GitHub Actions —— 来自环境机密的 API 密钥
- name: Sync inventory
shell: pwsh
env:
OPSKIT_API_TOKEN: ${{ secrets.OPSKIT_API_TOKEN }} # 运行器会在日志中屏蔽
run: ./scripts/Sync-OpsInventory.ps1
# 使用 OIDC 联合的 Azure —— 任何地方都不存储 Azure 机密
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
如何验证:运行之后,在作业日志和 ~/.../ConsoleHost_history.txt 中搜索令牌的前 8 个字符——应当什么都找不到。常见错误:调试时写 Write-Verbose "Headers: $($headers | ConvertTo-Json)"——CI 中加上 -Verbose 就会打印令牌(GitHub 会屏蔽已注册的机密,但不会屏蔽你的脚本从中派生出的令牌)。生产用途:OpsKit 的 Get-OpsApiToken(模块 8)先尝试 SecretManagement,再尝试 $env:OPSKIT_API_TOKEN,返回 SecureString,并且只记录令牌来自哪里。
目标:调用受保护的端点,而令牌从不出现在脚本、历史记录或输出中。环境:模拟 API 正在运行;SecretManagement 可选。费用:无。
$env:OPSKIT_API_TOKEN = Read-Host 'Mock API token (lab-token-7f3a)' -MaskInput
-MaskInput(PowerShell 7.1+)显示星号但返回字符串——适合放进环境变量。
$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(Get-PSReadLineOption).AddToHistoryHandler.Invoke('…') 测试三行你自己的命令。找出一行包含机密却返回 MemoryAndFile 的。(Get-Secret OpsKitApiToken -AsPlainText).Length 应打印 14。在模块 8 中,OpsKit 会自动取用该机密。Remove-Item Env:OPSKIT_API_TOKEN;如果你注册了实验保管库并想删除它:Remove-Secret OpsKitApiToken -Vault LabStore; Unregister-SecretVault LabStore。案例 1:脚本中的 PAT,一年后被机密扫描器发现
问题:某仓库的历史中包含一个“临时”脚本里的 $pat = 'ghp_…'。根因:用字面量测试,然后提交了。删掉那一行并不能把它从历史中移除。修复:先吊销令牌,如有需要再清理历史;启用推送保护 / 机密扫描;脚本只读取 $env: 或 Get-Secret。增加一套 PSScriptAnalyzer 规则(第 8 课),标记带字面量的 ConvertTo-SecureString -AsPlainText。
案例 2:重启后挂起的计划作业
问题:一个使用 SecretStore 的夜间作业运行了几周,服务器打补丁后永远挂起。根因:存储配置为 -Interaction Prompt;重启后它被锁定,Get-Secret 一直等待一个没人能输入的密码。修复:无人值守的存储使用 -Interaction None(被锁定的存储此时会抛出异常),每次运行开始时 Unlock-SecretStore,并使用 pwsh -NonInteractive(第 1 课),让任何提示快速失败。
案例 3:客户端机密过期导致所有部署停止
问题:所有流水线都以 AADSTS7000222: The provided client secret keys … are expired 失败。根因:一个两年有效期的服务主体机密存放在 40 条流水线中。修复:迁移到工作负载身份联合(OIDC):没有会过期或泄露的机密,信任范围限定在仓库和环境。仍需保留的机密集中存放在一个地方(Key Vault),并设置过期告警。
常见错误与修复
The cmdlet cannot protect plain text secrets sent over unencrypted connections
原因:对 http:// URI 使用了 -Authentication/-Credential。修复:使用 HTTPS。仅对本地测试 API 添加 -AllowUnencryptedAuthentication。
Cannot bind parameter 'Token'. Cannot convert … "System.String" to type "System.Security.SecureString"
-Token (ConvertTo-SecureString $env:API_TOKEN -AsPlainText -Force)
令牌明明正确却返回 401 Unauthorized
原因:令牌的受众/资源不对、令牌已过期(检查 exp 声明)、从文件读取时带了多余空白或尾随换行,或者重定向丢掉了该头(-PreserveAuthorizationOnRedirect)。响应中的 WWW-Authenticate 往往会说明是哪一种。
catch { $_.Exception.Response.Headers.WwwAuthenticate }Get-Secret: There are currently no extension vaults registered
原因:已安装 SecretManagement,但没有为当前用户注册保管库(服务账户有自己的注册表)。修复:以该账户身份执行 Register-SecretVault,或回退到环境变量(OpsKit 就是这样做的)。
作业挂在 Get-Secret 上
原因:SecretStore 已锁定且配置为提示。修复:Set-SecretStoreConfiguration -Interaction None,开始时 Unlock-SecretStore,以 -NonInteractive 运行。
1. 用一行命令、以 $env:OPSKIT_API_TOKEN 中的令牌调用模拟 API 的受保护端点,并且不打印令牌。
(Invoke-RestMethod "$base/api/secure/servers" -Authentication Bearer -Token (ConvertTo-SecureString $env:OPSKIT_API_TOKEN -AsPlainText -Force) -AllowUnencryptedAuthentication).count
2. 列出元数据中 purpose 包含 “pslab” 的所有机密名称,且不读取任何机密的值。
Get-SecretInfo | Where-Object { $_.Metadata['purpose'] -like '*pslab*' } | Select-Object Name, VaultName你的团队在 Azure Automation 中运行一个 PowerShell runbook,它调用 Azure API 和一个 SaaS 工单 API。目前两种凭据都是 Automation 账户中的变量。请提出更好的设计。
Azure:启用 Automation 账户的托管标识,在合适的范围授予它最小的 RBAC 角色,然后调用 Connect-AzAccount -Identity——不再保留任何 Azure 机密。SaaS API 密钥:存入 Key Vault,在该保管库上授予托管标识 Key Vault Secrets User,运行时读取(Get-AzKeyVaultSecret -AsPlainText 或使用带 Az.KeyVault 扩展的 SecretManagement)。日志中只记录使用了哪个标识和哪个机密名称,为密钥设置过期时间和告警,并在不修改 runbook 的情况下轮换它。
已验证的教学视频
官方文档
- SecretManagement 概述 · SecretStore 入门 · 在自动化中使用机密
- GitHub Actions 通过 OpenID Connect 连接 Azure · ConvertTo-SecureString
视频分镜(约 90 秒)
本教材无法直接生成视频或 MP3;分镜与旁白供视频工具使用。
画面:一个令牌字符串从脚本文件传到 Git、历史文件和日志——每处都打上红色标记。
旁白:令牌就是带有效期的密码。数一数它刚才在几个地方泄露了。
画面:四个来源框(保管库、环境变量、托管标识、OIDC)汇入同一个 SecureString。
旁白:加载它,在内存中保持安全,只通过 HTTPS 发送。
画面:Get-Secret 居中;SecretStore、Key Vault 和 KeePass 在后面接入。
旁白:代码只要一个名字;由配置决定哪个保管库来应答。
画面:GitHub 作业申请 id-token;Azure 返回短期访问令牌;屏幕上没有任何机密。
旁白:最好的机密,是你从未存储过的那一个。
模块 4 · Az PowerShell:登录方式、上下文与只读查询
- 按模块安装 Az(Az.Accounts + 所需的服务模块)并检查版本。
- 为每种情形选择
Connect-AzAccount参数集:交互式、-UseDeviceAuthentication、-Identity、带证书的服务主体、-FederatedToken。 - 读取并固定上下文:
Get-AzContext、Set-AzContext -Subscription、Disable-AzContextAutosave -Scope Process,以及在订阅不对时停止运行的防护。 - 执行只读查询(
Get-AzResourceGroup、Get-AzVM -Status),用-WhatIf预演变更;比较 Az 对象与azCLI 的 JSON 文本。
是什么:Az 模块家族
| 模块(实验机上的版本) | 提供 |
|---|---|
| Az.Accounts(5.5.0) | Connect-AzAccount、上下文、令牌缓存、Get-AzAccessToken、Invoke-AzRestMethod;其他所有模块都依赖它 |
| Az.Resources(10.0.0) | 资源组、通用资源、标签、部署、RBAC |
| Az.Compute(11.6.0) | VM、磁盘、映像、规模集 |
| Az.ResourceGraph(1.3.0) | Search-AzGraph(模块 7) |
| Az(16.0.0 汇总模块) | 安装 102 个模块;在工作站上方便,在 CI 映像和 Function 中浪费 |
为什么:上下文是看不见的状态
登录后,Az 会保存一个上下文:账户、租户、订阅、环境。所有未传 -DefaultProfile 的 cmdlet 都使用它。默认情况下上下文会保存到磁盘(~/.Azure),并在你所有的 pwsh 会话之间共享——因此在一个窗口中执行 Set-AzContext,会改变另一个窗口中正在运行的脚本的订阅。在自动化中:Disable-AzContextAutosave -Scope Process,登录,显式选择订阅,并断言它。
怎么做:Connect-AzAccount 参数集(来自 Az.Accounts 5.5.0 元数据)
| 参数集 | 必需参数 | 适用场景 |
|---|---|---|
UserWithSubscriptionId | — | 交互式:浏览器或 Windows 上的 WAM;在没有浏览器的远程 shell 中加 -UseDeviceAuthentication |
ManagedServiceLogin | -Identity | Azure VM、Function、Automation、Container Apps;用户分配的标识需加 -AccountId <clientId> |
ServicePrincipalCertificateWithSubscriptionId | -CertificateThumbprint -ApplicationId -Tenant | 自托管运行器 / 本地作业(证书在证书存储中) |
ServicePrincipalCertificateFileWithSubscriptionId | -ApplicationId -Tenant -CertificatePath | 带 PFX 文件的 Linux/macOS |
ClientAssertionParameterSet | -ApplicationId -Tenant -FederatedToken | OIDC:用 GitHub / Azure DevOps / Kubernetes 令牌换取 Azure 令牌 |
ServicePrincipalWithSubscriptionId | -Credential -ServicePrincipal -Tenant | 客户端机密(旧方式;优先用证书或联合) |
AccessTokenWithSubscriptionId | -AccessToken -AccountId | 你已经从别处拿到了令牌 |
何时用:Az PowerShell 还是 Azure CLI?
| Az PowerShell | 在 pwsh 中调用 az CLI | |
|---|---|---|
| 输出 | .NET 对象(PSResourceGroup、PSVirtualMachine) | JSON 文本行——已验证:az version --output json 返回字符串的 Object[];用管道传给 ConvertFrom-Json |
| 错误 | 错误记录(try/catch、-ErrorAction) | stderr + $LASTEXITCODE(第 5 课);$PSNativeCommandUseErrorActionPreference |
-WhatIf | New-/Remove-/Set-/Update- 类 cmdlet 支持 | 只有部分命令(az deployment … what-if) |
| 最适合 | PowerShell 管道、对象、OpsKit | 照抄文档示例、与 bash 保持一致 |
Connect-AzAccount 会选对订阅”——它选的是默认订阅(通常是第一个);一定要 Set-AzContext。② “上下文按窗口隔离”——默认是保存并共享的。③ “Remove-AzResourceGroup 的 -WhatIf 就足够审查了”——它告诉你目标是谁,而不是里面有什么;先列出资源。④ “必须 Install-Module Az”——只安装你用到的。⑤ “Get-AzVM 会显示电源状态”——只有加 -Status 才会(这是更慢的实例视图调用)。从登录到安全查询
登录方式 → 上下文 → 查询
每个场景展示一次运行如何认证、最终落到哪个订阅,以及防护是否拦住了错误。这里的输出均为预期输出(实验机上未登录云)。
IAzureContextContainer)记录要使用的账户、租户和订阅。每个 Az cmdlet 都接受 -DefaultProfile;省略时使用当前上下文。启用上下文自动保存时,上下文文件在同一用户的各个会话之间共享。命令表
| 命令 | 用途 | 说明 |
|---|---|---|
Install-PSResource Az.Accounts, Az.Resources, Az.Compute -Scope CurrentUser | 按模块安装 | 在 CI 中固定版本(-Version '[10.0.0, 11.0.0)') |
Connect-AzAccount -Tenant $t -Subscription $s | 交互式 | 没有浏览器时加 -UseDeviceAuthentication |
Connect-AzAccount -Identity [-AccountId $clientId] | 托管标识 | 仅限 Azure 托管的计算资源 |
Connect-AzAccount -ServicePrincipal -ApplicationId $a -Tenant $t -CertificateThumbprint $th | 证书服务主体 | Windows 证书存储;其他平台用 -CertificatePath |
Connect-AzAccount -ApplicationId $a -Tenant $t -FederatedToken $jwt | OIDC | 通常由 azure/login 代劳 |
Get-AzContext / Set-AzContext -Subscription $id | 读取 / 固定上下文 | 用 ID,不用名称 |
Disable-AzContextAutosave -Scope Process | 让本次运行的上下文保持私有 | 自动化的第一行 |
Get-AzResourceGroup [-Name] [-Tag @{owner='x'}] | 读取资源组 | 只读 |
Get-AzVM [-ResourceGroupName] [-Status] | VM 及其电源状态 | -Status 增加实例视图 |
New-/Remove-/Update-Az… -WhatIf | 预演 | 已验证:这些 cmdlet 支持 ShouldProcess |
1. 已安装了什么(真实元数据)
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. 登录方式就是参数集(真实元数据)
(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. 哪些 cmdlet 可以预演(真实元数据)
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 意味着在默认 $ConfirmPreference = 'High' 下不会自动提示。Remove-AzResourceGroup 和 Stop-AzVM 会自己询问 “Are you sure?”,除非你传 -Force——因此在 -NonInteractive 自动化中它们需要 -Force,这正是要先用 -WhatIf 运行的原因。
4. 带防护的会话(沙盒)
Disable-AzContextAutosave -Scope Process | Out-Null
$sub = '00000000-0000-0000-0000-000000000000' # 你的沙盒订阅 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. 只读查询
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. 预演变更
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 与 az:对象与文本(真实)
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
如何验证:每次登录后打印 (Get-AzContext).Subscription.Id,并与你期望的 ID 比较——不要比较名称,名称并不唯一。常见错误:在自动保存开启时,于一个终端执行 Set-AzContext,而另一个终端中正跑着长脚本。生产用途:每个 runbook 都以 Disable-AzContextAutosave -Scope Process 开头,使用适合宿主的登录方式(托管标识、OIDC),显式 Set-AzContext,并加上不匹配就抛出的防护;作业不需要改动任何东西时只授予 Reader。
目标:在不接触任何订阅的情况下探索 Az,然后(可选)运行一个带防护的只读会话。环境:已安装 Az.Accounts + Az.Resources + Az.Compute(或保存到某个文件夹)。费用:无;可选部分为只读。
$all = Get-Command -Module Az.Resources -CommandType Cmdlet
'{0} cmdlets, {1} with -WhatIf' -f $all.Count, @($all | Where-Object { $_.Parameters.ContainsKey('WhatIf') }).Count
数字取决于 Az.Resources 版本;比较 Get- 与 New-/Remove-/Set- 动词。
Get-Help Get-AzResourceGroup -Parameter Tag。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)"
}Assert-AzSubscription -Id $sub -Verbose Get-AzResourceGroup | Group-Object Location -NoElement | Sort-Object Count -Descending Get-AzVM -Status | Group-Object PowerState -NoElement
Disconnect-AzAccount(注销本进程的上下文)。没有创建任何东西。案例 1:清理作业删除了生产环境中的资源组
问题:一个“删除过期实验资源组”的夜间 runbook 删除了生产订阅中的资源组。根因:运行身份被授予了对第二个订阅的访问权限;Connect-AzAccount -Identity 把那个订阅选为默认,而脚本从未调用 Set-AzContext。标签过滤器还恰好匹配到一个旧的生产资源组。修复:显式 Set-AzContext + 防护;把 RBAC 最小权限限定在实验订阅;启用删除前先审查 -WhatIf 演练报告;给生产资源组加资源锁。
案例 2:构建要花 9 分钟的 CI 映像
问题:每次流水线运行都安装 Az(全部 100 多个模块)并导入。根因:一个只用三个 cmdlet 的作业却用了汇总模块。修复:安装 Az.Accounts + 用到的服务模块,固定版本并在运行之间缓存;用 #Requires -Modules 显式导入。
案例 3:因为保存的上下文而“在我机器上能跑”
问题:一个脚本对作者可以运行,对其他人都以 “Run Connect-AzAccount to login” 失败。根因:作者昨天保存的上下文;脚本从未登录。修复:脚本接受上下文或显式登录;在 Disconnect-AzAccount 之后或禁用自动保存的情况下用 pwsh -NoProfile 测试。
常见错误与修复
Run Connect-AzAccount to login.
原因:本进程中没有上下文(新的运行空间、禁用了自动保存、不同的用户)。修复:在脚本内用适合宿主的方式登录。
The subscription '…' could not be found / Set-AzContext 失败
原因:租户不对,或该身份在那个订阅上没有任何角色。修复:Get-AzSubscription -TenantId $t;检查 RBAC;给 Connect-AzAccount 传 -Tenant。
ManagedIdentityCredential authentication unavailable
原因:在 Azure 计算资源之外使用 -Identity,或标识未启用 / 未分配。对于用户分配的标识,传 -AccountId <clientId>。
AADSTS700213 / AADSTS70021: No matching federated identity record found
原因:OIDC 令牌的主体(仓库、分支、环境)与应用注册上的联合凭据不匹配。修复:逐字比较 sub 声明与凭据的主体(例如 repo:org/repo:environment:prod)。
Get-AzVM 没有返回 PowerState
原因:没有加 -Status。修复:Get-AzVM -Status;大规模环境用 Resource Graph 的 properties.extended.instanceView.powerState.code(模块 7)。
1. 显示使用 OIDC 令牌的那个参数集的必需参数。
((Get-Command Connect-AzAccount).ParameterSets | Where-Object Name -eq 'ClientAssertionParameterSet').Parameters |
Where-Object IsMandatory | Select-Object -ExpandProperty Name2. 列出沙盒中正在运行的 VM,只显示名称、资源组和规格。
Get-AzVM -Status | Where-Object PowerState -eq 'VM running' |
Select-Object Name, ResourceGroupName, @{ n = 'Size'; e = { $_.HardwareProfile.VmSize } }一位开发者想从自己的笔记本对一个共享订阅“就运行一次”清理脚本。在它运行之前你会要求什么?
① 显式上下文:Disable-AzContextAutosave -Scope Process、按 ID 执行 Set-AzContext,并加防护。② 用 -WhatIf 做一次演练,打印出每个目标,并由第二个人审查。③ 基于标记归属的标签(owner、expires)进行过滤,而不是基于名称模式。④ 对任何关键资源加资源锁。⑤ 理想情况下,用带受限身份的流水线来运行,而不是个人账户,这样有日志且可重复。
已验证的教学视频
官方文档
- 安装 Azure PowerShell · 使用 Azure PowerShell 登录 · 非交互式登录
- Connect-AzAccount · 上下文持久化 · Get-AzVM · Az PowerShell 与 Azure CLI
视频分镜(约 90 秒)
本教材无法直接生成视频或 MP3;分镜与旁白供视频工具使用。
画面:六扇登录之门(浏览器、设备代码、托管标识、证书、OIDC、机密)通向同一个名为“上下文”的房间。
旁白:入口很多,但之后的一切都由同一份状态决定。
画面:两个终端窗口共享同一个上下文文件;一个窗口切换订阅,另一个脚本的目标随之翻转。
旁白:上下文会被保存并共享。在自动化中禁用自动保存。
画面:订阅 ID 不匹配时,防护函数以红色抛出异常。
旁白:在任何查询或变更之前,按 ID 断言订阅。
画面:Get-AzVM 对象与 az CLI 的 JSON 文本,由 ConvertFrom-Json 连接起来。
旁白:Az 给你对象;CLI 给你需要转换的文本。
模块 5 · AWS.Tools:模块化安装、配置文件、区域与查询
- 用 AWS.Tools.Installer 只安装和更新需要的服务模块,并让它们保持同一版本。
- 预测 cmdlet 会使用哪套凭据(文档中的 V5 搜索顺序),并配置 profile 与 IAM Identity Center(SSO)。
- 用
-Region和Set-DefaultAWSRegion控制区域,并清楚区域还可能来自哪里。 - 查询 EC2 与 S3:拆开
Get-EC2Instance的 Reservation → Instances 结构,使用-Filter、-Select,并知道 V5 会自动遍历所有分页(手动分页用-NoAutoIteration)。
是什么:AWS 发布 PowerShell 的三种方式
| 包 | 说明 | 是否使用? |
|---|---|---|
| AWS.Tools.*(实验机上为 5.0.344) | 每个服务一个模块(AWS.Tools.EC2:843 个命令,AWS.Tools.S3:112 个——已验证),外加 AWS.Tools.Common;跨平台;支持自动加载 | 是 |
| AWS.Tools.Installer(2.0.6) | Install-AWSToolsModule、Update-AWSToolsModule、Uninstall-AWSToolsModule:让所有 AWS.Tools 模块保持同一版本,并能清理旧版本(-Cleanup) | 是,用来管理它们 |
| AWSPowerShell / AWSPowerShell.NetCore | 包含所有服务的旧式单一大模块 | 新项目不要用 |
为什么:V5 改变了一些你会注意到的行为
| V5 变更(AWS 迁移指南) | 对脚本的影响 |
|---|---|
| 统一的自动遍历:所有分页 cmdlet 默认取回全部页 | 大账号 → 调用时间长、API 请求多;自行分页用 -NoAutoIteration + -NextToken。已验证:Get-AWSAutoIterationMode 返回 standard |
| 可空值类型 | 未设置的数字/日期/布尔值为 $null,而不是 0 / 0001-01-01 / $false |
部分空集合变为 $null | 用 @(…),并用 $null -eq 判断(模块 7) |
移除 -PassThru;移除 $AWSHistory | 改用 -Select '^ParameterName' 或 -Select '*' |
凭据可来自 AWS_PROFILE / AWS_ACCESS_KEY_ID … 等环境变量;新的错误文本 “Failed to resolve AWS credentials” | 在 CI 中的行为与 AWS CLI 一致 |
| Ctrl+C 可取消 cmdlet | 交互体验更好 |
怎么做:凭据搜索顺序(V5,官方文档)
- 命令行上的明文密钥(
-AccessKey/-SecretKey)——避免使用。 -Credential(一个AWSCredentials对象,例如来自Use-STSRole)。- 用
Set-AWSCredential -ProfileName为会话设置的 profile(或 cmdlet 上的-ProfileName)。如果该 profile 不存在,命令会抛出异常——不会悄悄回退。 AWS_ACCESS_KEY_ID+AWS_SECRET_ACCESS_KEY+AWS_SESSION_TOKEN(三者都要有)。AWS_PROFILE指定的 profile。defaultprofile(先 SDK store,再共享凭据文件,最后AWS PS Default)。- EC2 实例配置文件(IAM 角色)凭据。
区域单独解析:调用上的 -Region → Set-DefaultAWSRegion 设置的 shell 默认值($StoredAWSRegion)→ AWS_REGION/AWS_DEFAULT_REGION → profile 中的 region → 实例元数据。区域错了并不会报错:你只会看到一个空列表。
何时用:人用 SSO profile,机器用角色
人:用 aws configure sso(或 Initialize-AWSSSOConfiguration)创建 IAM Identity Center profile,然后由 Invoke-AWSSSOLogin / CLI 登录刷新短期凭据。机器:实例配置文件、ECS 任务角色、Lambda 执行角色,或配合 aws-actions/configure-aws-credentials 的 GitHub OIDC——磁盘上不放访问密钥。
Get-EC2Instance 返回实例”——它返回的是 Reservations;实例在 .Instances 里(已验证 OutputType:Amazon.EC2.Model.Reservation)。② “结果为空说明没有资源”——往往是区域或账号不对。③ “Install-Module AWSPowerShell.NetCore 是现代做法”——应使用 AWS.Tools.*。④ “自动遍历不花钱”——有多少页就发多少次 API 调用,每次都计入限流配额。⑤ “Set-AWSCredential -StoreAs 是安全的保管库”——它写入 SDK store/凭据文件;优先使用 SSO 和角色。凭据与区域的解析
凭据与区域的解析
跟随一次 Get-EC2Instance 调用,走过凭据链、区域链和分页。云端输出均为预期输出。
AWSCredentials 对象和一个 RegionEndpoint,构造 SDK 客户端(例如 AmazonEC2Client)并调用 API。对于分页操作,除非设置了 -NoAutoIteration,cmdlet 会按 NextToken 循环,把每页的条目写入管道。-Select 决定从每个响应中输出什么(Get-EC2Instance 默认为 Reservations)。命令表
| 命令 | 用途 | 说明 |
|---|---|---|
Install-AWSToolsModule EC2, S3, SecurityToken -Cleanup | 安装服务模块(+ Common) | 全部同一版本;-Cleanup 删除旧版本 |
Update-AWSToolsModule -Cleanup | 更新所有已安装的 AWS.Tools | 默认升级到 V5;要留在 V4 用 -MaximumVersion '4.9.999' |
Set-AWSCredential -ProfileName dev-sso | 会话默认 profile | profile 不存在时抛出异常 |
Invoke-AWSSSOLogin / Initialize-AWSSSOConfiguration | IAM Identity Center | 或 aws sso login --profile … |
Set-DefaultAWSRegion -Region ca-central-1 | 会话默认区域 | Get-DefaultAWSRegion、$StoredAWSRegion |
Get-AWSRegion | 区域列表(离线,来自 SDK) | 5.0.344 中有 45 个区域 |
Get-EC2Instance -Filter @{Name='tag:env';Values='prod'} | 服务端过滤 | 返回 Reservations |
Get-EC2Instance -Select 'Reservations.Instances' | 在 cmdlet 内拆包 | -Select '*' = 完整响应 |
Get-S3Bucket [-BucketRegion] | 列出存储桶 | 全局列表;各桶区域不同 |
-NoAutoIteration -NextToken $t -MaxResult 100 | 手动分页 | 用 -Select '*' 查看 NextToken |
1. 模块与版本(真实;保存到文件夹,见模块 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. 区域默认值是本地状态(真实,不调用 AWS)
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. Get-EC2Instance 返回什么、接受什么(真实元数据)
(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. 用 SSO profile 登录并查询(沙盒)
# 一次性:aws configure sso (在 ~/.aws/config 中创建 profile 'pslab-sso')
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 # reservation 数
$res.Instances.Count # 实例数
$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 与 -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. 没有凭据(CI 中缺少角色时看到的情况)
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: …
如何验证:每次运行开始时都打印 (Get-STSCallerIdentity).Arn 和区域——相当于 AWS 版的 Az 上下文守卫。常见错误:(Get-EC2Instance).InstanceId 什么也不返回,因为 reservation 上没有这个属性;应使用 .Instances.InstanceId。生产用途:在 CI 中固定 AWS.Tools.* 版本;在跨多个区域运行的脚本中显式传入 -Region(foreach ($r in $regions) { Get-EC2Instance -Region $r });机器使用角色或 OIDC;估算 API 调用量时考虑自动遍历。
目标:先离线熟悉 AWS.Tools 的数据结构,再(可选)查询沙盒。环境:AWS.Tools.EC2 + Common(已安装或保存到文件夹)。费用:无;Describe/List 调用免费。
Get-Command -Module AWS.Tools.EC2 -Verb Get -Noun EC2Instance* | Select-Object -ExpandProperty Name
$StoredAWSRegion 为空——默认值是按会话生效的。~/pslab/tmp/ec2-describe.json 与 Get-EC2Instance -Select '*' 的结构相同)。$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
}Clear-DefaultAWSRegion;Clear-AWSCredential(仅限当前会话)。没有创建任何资源。案例 1:“丢了”一半机群的资产清单
问题:一份合规报表列出 120 个实例,控制台显示 240 个。根因:作业在 runner 上以 AWS_DEFAULT_REGION=us-east-1 运行,而一半机群在 ca-central-1。没有报错——只是一个空区域。修复:显式的区域列表(或用 Get-EC2Region 获取已启用区域),并在每次调用上都传 -Region;报表打印它查询的区域和账号。
案例 2:profile 名拼错,回退到了管理员密钥
问题:在一台 V3 时代的老跳板机上,一个 profile 名拼错的脚本用 default profile 运行了——而那里存着长期有效的管理员密钥。根因:回退链 + 权限过大的默认值。修复:主机上不放长期密钥(用 SSO、角色);当前版本的工具在使用 Set-AWSCredential -ProfileName 时,profile 不存在会抛异常,所以要显式设置而不是依赖 default;default profile 不给任何权限。
案例 3:事故期间 DescribeInstances 被限流
问题:一次故障中,十位工程师运行同一个“列出一切”的脚本;EC2 API 开始返回 RequestLimitExceeded,拖慢了事故处理工具。根因:对数千个实例反复自动遍历,且没有过滤。修复:服务端 -Filter、缓存的资产清单(把 Get-OpsCloudInventory 的输出保存为 JSON),以及遇到限流错误时退避。
常见错误与修复
Failed to resolve AWS credentials …
原因:凭据链中什么都没找到。修复:aws sso login --profile p + -ProfileName p,或在 CI 中加上角色/OIDC 步骤。检查 $env:AWS_PROFILE。
The SSO session associated with this profile has expired or is otherwise invalid
修复:aws sso login --profile p(或 Invoke-AWSSSOLogin);SSO 凭据本来就是短期的。
No region specified or obtained from persisted/shell defaults
Set-DefaultAWSRegion -Region ca-central-1 # 或在每次调用上传 -Region
(Get-EC2Instance).InstanceId 为空
(Get-EC2Instance).Instances.InstanceId
Import-Module: Assembly with same name is already loaded(AWS.Tools.* 版本混用)
原因:同一会话中存在两个 AWS.Tools 版本。修复:Update-AWSToolsModule -Cleanup;开启一个新会话。
1. 在一张表中列出两个区域里所有运行中实例的 ID 和 Name 标签。
'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. 打印当前会话使用的身份,且不列出任何资源(Get-STSCallerIdentity 位于 AWS.Tools.SecurityToken)。
Get-STSCallerIdentity | Select-Object Account, Arn
一个使用 AWS.Tools 的 GitHub Actions 作业在 main 上正常,但在来自 fork 的拉取请求上报凭据错误。为什么?正确的设计是什么?
使用 OIDC 时,IAM 角色的信任策略会限制令牌的 sub 声明(仓库、分支、环境);fork 的 PR 要么拿不到 id-token 权限,要么 subject 不匹配——这是正确的行为。保持它:PR 的只读检查可以使用一个单独的、范围很窄、信任 pull_request 的角色;任何有写权限的操作只在受保护的分支/环境上运行。绝不要通过把访问密钥加到仓库机密来“修复”它。
已验证的教学视频
官方文档
视频分镜(约 90 秒)
本教材无法直接生成视频或 MP3;分镜与旁白可交给视频工具使用。
画面:一排小模块(EC2、S3、IAM)取代一个巨大的箱子。
旁白:只安装你用到的服务,全部保持同一版本。
画面:七级凭据阶梯;一次调用逐级向上,直到找到匹配。
旁白:凭据按固定顺序解析。要清楚自己停在哪一级。
画面:一个 Reservation 盒子打开,露出多个 Instance 盒子。
旁白:Get-EC2Instance 返回的是 reservation,实例在里面。
画面:一张世界地图;只有一个区域亮着,其余为空,报表上写着“120”。
旁白:区域错了不是错误,而是一个空答案。
模块 6 · 幂等的云变更:先查后改、标签与 ShouldProcess
- 编写“读取 → 比较 → 设置”函数,第二次运行时报告
Changed = $false。 - 把标签用作归属与生命周期元数据,并以合并而非替换的方式写入(
Update-AzTag -Operation Merge、New-EC2Tag)。 - 把 Az/AWS cmdlet 包装进
SupportsShouldProcess函数,并了解已验证的陷阱:脚本的-WhatIf和-Verbose不会传到模块中的函数,除非你显式传递。 - 专门处理“不存在”(状态码 404、
ResourceGroupNotFound、InvalidInstanceID.NotFound),其他任何错误都让运行停止。
是什么:一句话说明幂等
同一操作运行一次或十次,系统状态都相同,而且第一次之后的运行都报告“无变化”。声明式工具(Bicep、Terraform)替你做到这一点;PowerShell 脚本必须自己做到。
| 模式 | 幂等吗? | 原因 |
|---|---|---|
每次运行都执行 New-AzResourceGroup -Name x | 部分幂等——Azure 会更新已有的资源组,但你传入的标签会替换原有标签 | 各 API 的“创建或更新”语义不同 |
每次运行都 POST /items | 否——产生重复项或 409 | POST 用于创建 |
用完整期望状态 PUT /items/x | 是(按 HTTP 定义) | PUT 用相同内容替换 |
| GET → 比较 → 只对差异做 PUT/PATCH | 是,并且可以报告和预演 | 本模块的模式 |
为什么:标签让自动化知道哪些资源归它管
给你创建的一切打标签:owner、managedBy=opskit、env、expires、costCenter。清理和同步作业只处理带 managedBy=opskit 的资源,绝不依据名称模式。以合并方式写标签(Update-AzTag -Operation Merge;New-EC2Tag 只新增/覆盖给定的键),其他团队的标签才能保留。
怎么做:“不存在”是数据,其他错误是故障
| 来源 | “不存在”的表现(模拟 API 已验证;云端为预期) | 处理方式 |
|---|---|---|
| REST / 模拟 API | HttpResponseException,StatusCode = NotFound | catch [Microsoft.PowerShell.Commands.HttpResponseException] + 检查状态码;其他情况重新抛出 |
| Az | Get-AzResourceGroup -Name x:“Provided resource group does not exist.” | -ErrorAction SilentlyContinue -ErrorVariable e,然后检查 $e;或用 Get-AzResourceGroup | Where-Object / Resource Graph 查询(为空 = 不存在) |
| AWS | AmazonEC2Exception,ErrorCode = InvalidInstanceID.NotFound | catch [Amazon.EC2.AmazonEC2Exception] { if ($_.Exception.ErrorCode -like '*.NotFound') … else { throw } } |
何时注意:首选项变量传递陷阱(已验证)
用 -WhatIf -Verbose 运行的脚本会在脚本作用域中设置 $WhatIfPreference 和 $VerbosePreference。脚本中定义的函数能看到它们;从模块导出的函数看不到——它们先在模块作用域、再在全局作用域中查找变量。在 7.6.10 上验证:脚本以 -WhatIf 运行时,模块函数真的执行了变更。修复方法:在脚本中调用 ShouldProcess,再以 -Confirm:$false 调用模块函数;或者把开关传下去:-WhatIf:$WhatIfPreference -Verbose:($VerbosePreference -eq 'Continue')。综合实验中的 Sync-OpsInventory.ps1 两种都用了。
-ErrorAction SilentlyContinue 就能判断是否存在”——它同样会隐藏 401、限流和拼写错误(模块 1,案例 2)。② “给脚本加 -WhatIf,里面的一切都安全了”——模块函数不受影响,原生工具(az、aws)也不受影响。③ “传给 New-… 的标签会被合并”——对已有资源组执行 New-AzResourceGroup -Tag 会替换整个标签集合。④ “幂等就是第二次运行不报错”——幂等意味着没有变更;第二次运行因 409 而失败的创建操作不是幂等,只是运气好。⑤ “用 -eq 比较就够了”——某些提供方的标签值是区分大小写的字符串;应使用 -ceq 并统一类型。读取 → 比较 → 设置
首选项变量在哪里可见
先查后改的决策路径
针对模拟 API 运行 Set-LabServerTag(真实),以及围绕 Az 的同一模式(预期)。
$PSCmdlet.ShouldProcess() 会检查调用方的 -WhatIf/-Confirm,以及函数自身作用域链中可见的 $WhatIfPreference/$ConfirmPreference。对脚本中的函数,这条链包括脚本作用域;对模块中的函数,则是模块作用域 → 全局作用域。带类型的 catch [HttpResponseException] 按异常类型匹配,因此其他故障(连接被拒:HttpRequestException)会直接传给调用方。命令表
| 命令 | 用途 | 说明 |
|---|---|---|
[CmdletBinding(SupportsShouldProcess)] + $PSCmdlet.ShouldProcess($target, $action) | 预演 / 确认写操作 | GET 和比较放在外面,写操作放在里面 |
catch [Microsoft.PowerShell.Commands.HttpResponseException] | 只处理 HTTP 状态错误 | 再检查 .Response.StatusCode |
Update-AzTag -ResourceId $id -Tag $t -Operation Merge | 在 Azure 中合并标签 | 另有 Replace / Delete |
Get-AzResourceGroup -Name $n -ErrorAction SilentlyContinue -ErrorVariable e | 带证据的存在性检查 | 检查 $e,不要忽略它 |
New-EC2Tag -Resource $id -Tag @{Key='owner';Value='x'} | 新增/覆盖 AWS 标签 | 其他键保持不变 |
-WhatIf:$WhatIfPreference -Verbose:($VerbosePreference -eq 'Continue') | 把首选项传给模块函数 | 或使用展开传参 @vb |
Set-LabServerTag:针对模拟 API 的读取 → 比较 → 设置
保存为 ~/pslab/scripts/Set-LabServerTag.ps1,然后点源(dot-source)加载。
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)
合并在修改 owner 的同时保留了 managedBy;不存在的服务器只产生一条警告;连接被拒(是 HttpRequestException,不是 HttpResponseException)直接越过带类型的 catch 传给了调用方。
复现首选项陷阱
# ~/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".
围绕 Az 的同一模式(沙盒)
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] } # 认证、限流、拼写错误……
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
如何验证:每个变更函数都运行三次——-WhatIf、真实执行、再真实执行一次——并要求第三次报告无变化。常见错误:使用 -ErrorAction SilentlyContinue 却不加 -ErrorVariable:令牌过期时看起来就像“不存在”,函数于是尝试去创建。生产用途:定时同步作业每晚以 -WhatIf 运行并输出报表(漂移检测),只在评审后才以“应用”模式运行;它们只处理带 managedBy=opskit 标签的资源。
目标:让一个变更函数成为幂等,并加以证明。环境:模拟 API 正在运行。费用:无。
staging/api-01 运行 Set-LabServerTag 三次(WhatIf、应用、应用),标签为 @{ owner = 'team-api'; expires = '2026-12-31' }。第三次必须显示 Changed = False。@{ costCenter = 'cc-200' } 后读取标签;owner 和 expires 必须仍然存在。
(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
~/pslab/tmp 中创建“命令”页中的两个文件,运行 & ~/pslab/tmp/caller.ps1 -WhatIf,找出不该出现的那一行。-WhatIf:$WhatIfPreference;② 在脚本自己的 if ($PSCmdlet.ShouldProcess(…)) 中包裹调用,并以 -Confirm:$false 调用模块函数。用 -WhatIf 重新运行:不再出现 “CHANGED” 行。Remove-Item ~/pslab/tmp/PrefDemo, ~/pslab/tmp/caller.ps1 -Recurse。标签只存在于模拟 API 的内存中,停止后即消失。案例 1:改动了生产环境的“演练”
问题:一张变更单要求附上 ./Rotate-Keys.ps1 -WhatIf 的输出作为证据。结果这次演练真的轮换了密钥。根因:脚本调用了公司模块中的 Reset-OpsKey;脚本的 $WhatIfPreference 从未到达该模块函数。修复:在脚本中为每个调用包上 ShouldProcess,并在内部调用上加 -Confirm:$false;再加一个 Pester 测试(第 8 课),以 -WhatIf 针对模拟对象运行脚本,并断言写调用次数为零。
案例 2:标签被重新部署清空
问题:资源组上的财务标签每周一都会消失。根因:一个每周运行的脚本执行 New-AzResourceGroup -Name … -Tag @{ env = 'prod' } -Force,替换了整个标签集合。修复:只在不存在时创建;用 Update-AzTag -Operation Merge 维护标签;必需标签改用 Azure Policy 强制,而不是靠脚本。
案例 3:清理作业删错了虚拟机
问题:“删除名为 tmp-* 且超过 7 天的虚拟机”删掉了供应商的 tmp-sql01。根因:根据名称推断归属。修复:只处理由创建它的自动化写入的 managedBy=opskit 和 expires 标签;先出报表,宽限期过后再删除。
常见错误与修复
我的脚本加了 -WhatIf,仍然改动了东西
原因:写操作由模块函数或原生工具执行。修复:传 -WhatIf:$WhatIfPreference,或在调用方使用 ShouldProcess;原生工具需要使用它们自己的演练参数。
第二次运行产生了重复项,或以 409 Conflict 失败
原因:创建前没有检查。修复:先 GET(或使用确定性 ID 的 PUT);只有当已存在的对象与期望一致时,才把 409 视为“已存在”。
catch [HttpResponseException] 从未执行
原因:故障是 HttpRequestException(网络)或 TaskCanceledException(超时)。这通常正是你想要的:它们不属于“不存在”。
Update-AzTag: The client '…' does not have authorization to perform action 'Microsoft.Resources/tags/write'
原因:只有 Reader 角色。修复:在合适的范围授予 Tag Contributor——对只处理标签的自动化来说,这是比 Contributor 更窄的角色。
标签比较总是显示“已变更”
原因:拿 Hashtable 和 PSCustomObject 比较,或值的类型/大小写不同。修复:统一转成字符串并逐键比较(-ceq),就像 Set-LabServerTag 那样。
1. 写一个带类型的 catch:404 时返回 $null,其他情况重新抛出。
try { Invoke-RestMethod $uri }
catch [Microsoft.PowerShell.Commands.HttpResponseException] {
if ($_.Exception.Response.StatusCode -eq 'NotFound') { $null } else { throw }
}2. 在一个带 SupportsShouldProcess 的脚本中调用模块函数,使脚本的 -WhatIf 和 -Verbose 生效。
$common = @{ WhatIf = $WhatIfPreference; Verbose = $VerbosePreference -eq 'Continue' }
Set-OpsThing -Name x @common一个夜间作业从 CMDB 复制 owner 标签,确保每个资源组都有它。有些晚上报告 300 处变更,有些晚上为 0,尽管没人改过标签。请排查。
很可能是比较不幂等:例如 CMDB 返回 "Team-Web",Azure 存的是 "team-web",而代码只在一侧使用 -ceq;或者 CMDB API 分页,某些晚上返回的行更少(没有分页循环,模块 2),于是作业把标签“修复”成空值/默认值。检查:为一个反复变化的资源组记录期望值与当前值;核对 CMDB 返回的行数与其总数;统一大小写规则;期望值缺失时绝不写入——把缺失的输入当作错误,而不是“删除标签”。
已验证的教学视频
没有找到演示首选项变量传入模块函数的已验证视频;请以本模块的复现为准。
官方文档
- about_Functions_CmdletBindingAttribute(SupportsShouldProcess) · about_Preference_Variables
- Update-AzTag
视频分镜(约 90 秒)
本教材无法直接生成视频或 MP3;分镜与旁白可交给视频工具使用。
画面:同一个脚本运行三次;计数器显示“2 处变更、0、0”。
旁白:幂等意味着第二次运行不改变任何东西。
画面:GET、比较、ShouldProcess、PUT 四道门;只有存在差异时最后两道门才打开。
旁白:读取、比较、预演,然后只写入差异。
画面:一把 WhatIf 雨伞罩着脚本;一个模块函数站在伞外淋雨。
旁白:首选项不会进入模块。要把它们传下去。
画面:一个 404 落进“不存在”托盘,一个 401 触发了警报。
旁白:不存在是数据;其他一切都应让运行停止。
模块 7 · 云数据处理:整形 JSON、Resource Graph 与报表
- 用成员枚举和
Select-Object -ExpandProperty展平嵌套数组,用计算属性展平嵌套对象。 - 把标签数组(
[{Key,Value}],AWS)和标签对象({env: …},Azure)转换成列。 - 用
Search-AzGraph查询 Azure Resource Graph:KQL 的project/where/summarize,-First最多 1,000,以及-SkipToken分页。 - 导出报表:只在展平之后使用
Export-Csv,ConvertTo-Json -Depth,并了解空集合计数陷阱。
What:你会遇到的三种形状
| 形状 | 示例 | 展平方式 |
|---|---|---|
| 信封 + 列表 | { value: [...], nextLink }、{ data: [...], skipToken }、{ Reservations: [...] } | .value / .data(处理完分页之后) |
| 列表套列表 | Reservations → Instances(AWS);VM → NIC → IP 配置(Azure) | 成员枚举 $r.Reservations.Instances 或 Select-Object -ExpandProperty Instances |
| 对象套对象 | properties.hardwareProfile.vmSize、State.Name | 计算属性 @{ n = 'size'; e = { $_.properties.hardwareProfile.vmSize } } |
| 键/值列表形式的标签 | AWS Tags: [{Key:'Name',Value:'web-01'}] | ($_.Tags | Where-Object Key -eq 'Name').Value |
| 对象形式的标签 | Azure tags: { env: 'prod' } | $_.tags.env;缺失的标签 → $null(?? '(none)') |
Why:CSV 装不下嵌套
Export-Csv 对每个属性调用 ToString():嵌套对象会变成 @{env=prod; owner=team-web},更深一层会变成 @{hardwareProfile=; extended=}(下文已验证)。务必先选出扁平属性,再导出。对于 JSON,输出时要传 -Depth——ConvertTo-Json 在第 2 层截断,只给出一条警告。
How:用 Resource Graph 代替 N×M 次 API 调用
通过 Get-AzVM -Status 列出 50 个订阅中 VM 的电源状态,意味着数百次 ARM 调用和反复切换上下文。Azure Resource Graph 为你有读取权限的每个订阅建立资源属性索引,一次调用就能回答一个 KQL 查询(已验证:Search-AzGraph -First 接受 1–1000;响应是一个带 Data 和 SkipToken 的列表)。它只读、免费、速度快——但略有延迟(变更后几秒到几分钟),并且仅限于 Resource Graph 索引的内容。
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:控制成本的报表做法
- 优先使用列表/查询类 API(Resource Graph、Describe*、List*)——它们免费且只读。
- 在服务端过滤(EC2 用
-Filter,KQL 用where),而不是全部下载后在 PowerShell 里过滤——页数更少,限流更少。 - 缓存:把整形后的清单写入 JSON 一次,多次基于文件出报表。
- 成本数据本身(Cost Management、Cost Explorer)在 AWS 上按请求计费——不要在循环里轮询。
@($x.Items).Count 总是安全的”——如果 $x.Items 是空数组,对空列表做成员枚举返回 $null,而 @($null).Count 是 1(下文已验证)。② “Export-Csv 能处理对象”——只能处理扁平对象。③ “Resource Graph 是实时的”——它是最终一致的。④ “KQL 的 == 不区分大小写”——== 区分大小写,=~ 不区分;资源类型有的地方是小写,有的地方大小写混合。⑤ “-ExpandProperty 会保留父对象的属性”——它输出的是子对象(只有在你同时选择父属性时才会附加上去,而且可能冲突)。从原始 JSON 到报表
Resource Graph 与逐订阅调用
从原始 JSON 到报表
逐步查看每条整形管道;红色表示该步骤丢失了数据。
$list.Property)替你执行循环,收集每个元素的该属性;嵌套数组会被展平一层。对空集合它什么也不产生,在表达式上下文中就变成 $null。Export-Csv 按第一个对象的属性每个写一列,并对每个值调用 ToString();PSCustomObject.ToString() 产生的就是你看到的 @{…} 文本。命令表
| 命令 | 用途 | 说明 |
|---|---|---|
Get-Content f -Raw | ConvertFrom-Json [-AsHashtable] [-Depth n] | 解析 | 7.6 上 -AsHashtable → OrderedHashtable(已验证) |
$x.Reservations.Instances | 通过成员枚举展平 | 空列表陷阱:用不带 @() 的 .Count 或 ForEach-Object |
Select-Object -ExpandProperty Instances | 在管道中展平 | 以流的方式输出子对象 |
Select-Object @{ n = 'x'; e = { $_.a.b.c } } | 计算列 | 用 ?? 提供默认值 |
.Where({ … })、.ForEach({ … }) | 快速的内存内过滤 | 可用于嵌套集合 |
Search-AzGraph -Query $kql -First 1000 [-SkipToken $t] [-Subscription …] [-ManagementGroup …] [-UseTenantScope] | Resource Graph | 响应:列表 + .SkipToken、.Data |
Export-Csv -NoTypeInformation | 扁平报表 | 7.x 默认省略类型行 |
ConvertTo-Json -Depth 10 | Set-Content | 结构化报表 | 用 ConvertFrom-Json 做往返测试 |
创建两个示例文件
结构与 Get-EC2Instance -Select '*' / aws ec2 describe-instances 以及 Resource Graph 响应相同。数值均为虚构。
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 → 行
$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
对于真实的 Get-EC2Instance 对象,State.Name 是一个 InstanceStateName 类:用 $_.State.Name.Value 取字符串。
Resource Graph:嵌套属性和标签 → 报表
$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
导出:扁平 CSV 正常,嵌套 CSV 不行
$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 深度、哈希表与空集合陷阱
$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(沙盒)
Import-Module Az.ResourceGraph
(Get-Command Search-AzGraph).OutputType.Type.Name # 真实:无需登录
$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
如何验证:把 $rows.Count 与 KQL 的 | count 查询结果对比;对于 EC2,与控制台中相同区域、相同过滤条件下的实例数对比。常见错误:把 Search-AzGraph 或 Get-AzVM 的输出直接导出为 CSV——得到的是类型名和 @{…} 文本块。生产用途:夜间作业运行 Resource Graph / Describe 查询,把结果整形为扁平的 OpsKit.CloudResource 行(模块 8),给机器写 JSON、给人写 CSV,并对比今天与昨天以发现漂移。
目标:用两个示例文件生成一份扁平的 VM 报表。环境:只需 pwsh。费用:无。
Cloud, Name, Env, Size, State),然后排序。
$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
Group-Object Cloud, State -NoElement 按 Cloud, State 计数;列出所有未在运行的项。$rows | Export-Csv ~/pslab/tmp/fleet.csv 和 $rows | ConvertTo-Json | Set-Content ~/pslab/tmp/fleet.json;重新导入两者,确认各有 7 行。Remove-Item ~/pslab/tmp/*.csv, ~/pslab/tmp/fleet.json(保留两个示例文件,供模块 5 离线练习使用)。案例 1:没人能筛选的合规 CSV
问题:一份“所有 VM 及其标签”的审计导出只有一列 Tags,内容是 System.Collections.Generic.Dictionary`2[…]。根因:Get-AzVM | Export-Csv。修复:先确定列(每个必需标签一列),用计算属性展平,再导出;加一个测试:任何单元格以 @{ 或 System. 开头就失败。
案例 2:“0 台已停止实例”其实是 1
问题:一个仪表板在一个根本没有实例的账号里显示有一台已停止实例。根因:@($resp.Reservations.Instances | Where-Object …).Count 没问题,但另一个指标在空账号上用了 @($resp.Reservations.Instances).Count → 1。修复:对枚举结果用 .Count 计数,或通过管道交给 Measure-Object;显式测试空的情况。
案例 3:拖垮所有人 ARM 配额的清单作业
问题:一个用 Get-AzVM -Status 跨 80 个订阅做全租户 VM 清单的作业运行了 40 分钟,并让其他自动化收到 429。根因:逐台 VM 的实例视图调用。修复:改为一次带分页的 Resource Graph 查询;作业现在一分钟内完成,只发出寥寥几次调用。
常见错误与修复
CSV 中出现 @{…} 或 System.Object[]
修复:先展平;把数组拼接起来:@{ 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 / 没有结果
原因:未登录、租户不对,或在查询范围内没有读取权限。修复:Get-AzContext;显式传入 -Subscription 或 -ManagementGroup。
Resource Graph 只返回 100(或 1,000)行
原因:默认页大小 / 没有 SkipToken 循环。修复:-First 1000 + 基于 .SkipToken 循环。
JSON 里有这个属性,读出来却是空的
原因:大小写或名称不匹配(properties 与 Properties 在 PowerShell 中没问题,但 @odata.nextLink 需要加引号:$r.'@odata.nextLink'),或者值比你以为的还要深一层。修复:用 $x | ConvertTo-Json -Depth 3 查看真实形状。
1. 用 EC2 示例,列出每个实例 ID,并把它的所有标签拼成一个 key=value;… 字符串。
$ec2.Reservations.Instances | Select-Object InstanceId,
@{ n = 'Tags'; e = { ($_.Tags | ForEach-Object { "$($_.Key)=$($_.Value)" }) -join ';' } }2. 写一个 KQL 查询,按 env 标签统计 VM 数,未打标签的 VM 归入“(none)”。
Resources | where type =~ 'microsoft.compute/virtualmachines' | extend env = iff(isempty(tostring(tags.env)), '(none)', tostring(tags.env)) | summarize count() by env
管理层希望每周得到一份 Azure 和 AWS 上“每台 VM 的负责人与成本中心”报表。请设计它。
输入:Resource Graph(一个 KQL 查询,带分页)以及按每个已启用区域执行的 Get-EC2Instance(服务端过滤)。把两者整形为同一个对象模型(Cloud, Account/Subscription, Region, Name, Owner, CostCenter, State, Id)——这正是模块 8 中 Get-OpsCloudInventory 做的事。写出 JSON(机器可读,保留以便逐周对比)和 CSV(给人看)。把缺少负责人/成本中心的行单独列为一节。使用只读身份,避开高峰时段调度,并记录每个数据源的行数,以便及时发现某个数据源悄悄变空。
已验证的教学视频
官方文档
视频分镜(约 90 秒)
本教材无法直接生成视频或 MP3;分镜与旁白可交给视频工具使用。
画面:一棵五层的 JSON 树折叠成一行扁平的表格。
旁白:API 说的是树,报表说的是行。
画面:Reservations 盒子打开,露出 Instances;标签列表变成 Name 和 Env 两列。
旁白:拆开列表,用计算属性取出嵌套的值。
画面:一个显示 @{env=prod…} 的 CSV 单元格被打上红叉。
旁白:导出前先展平,并给 JSON 指定深度。
画面:80 个订阅图标,一个 KQL 查询,一个答案。
旁白:做清单时,问 Resource Graph 一次,而不是把每个 API 问很多次。
模块 8 · OpsKit v0.5:Invoke-OpsApi 与 Get-OpsCloudInventory
- 向 OpsKit 模块添加两个公共函数和一个私有辅助函数,并用
Update-PSModuleManifest把清单版本提升到 0.5.0。 - 实现
Invoke-OpsApi:令牌来自 SecretManagement 或$env:OPSKIT_API_TOKEN;明文 HTTP 仅限环回地址;基于-SkipHttpErrorCheck的状态分类;被Retry-After覆盖的指数退避;POST 只在明确要求时重试;-All分页;写操作走 ShouldProcess;清晰的终止性错误。 - 实现
Get-OpsCloudInventory:来自 Local / Api / Azure / Aws 数据源、带统一Key的OpsKit.CloudResource对象;云数据源不可用时给出警告并跳过。 - 使用交互式排错树诊断 API 自动化故障。
~/pslab/OpsKit 中的 OpsKit v0.4。重要程度:★★★★★What:OpsKit v0.5 的目录结构
| 文件 | 0.5 新增 | 作用 |
|---|---|---|
Private/Get-OpsApiToken.ps1 | ✓ | SecureString 令牌:SecretManagement 机密 OpsKitApiToken → $env:OPSKIT_API_TOKEN → $null;只记录来源 |
Public/Invoke-OpsApi.ps1 | ✓ | 其他所有功能都使用的 REST 客户端 |
Public/Get-OpsCloudInventory.ps1 | ✓ | 合并后的清单;只读 |
OpsKit.psd1 | 0.5.0,新增两个导出 | Update-PSModuleManifest(PSResourceGet) |
Public/Get-OpsServer.ps1、Get-OpsConfig.ps1、…(v0.1–v0.4) | — | 复用:Get-OpsServer 就是 Local 数据源 |
Why:每个设计决策都来自前面的模块
| 决策 | 理由(模块) |
|---|---|
用 -SkipHttpErrorCheck -StatusCodeVariable -ResponseHeadersVariable 代替 try/catch | HTTP 错误是终止性错误;我们要的是分类,而不是捕获(M1) |
重试集合为 408/429/500/502/503/504 + 网络错误;不用内置的 -MaximumRetryCount | 内置重试会重试 404 和 POST,却不重试超时(M2) |
Retry-After 覆盖退避值 0.5 × 2^(n−1) | 限流(M2) |
POST 只在指定 -RetryNonIdempotent 时重试 | 重复创建(M2 案例 3) |
令牌保持为 SecureString,从不记录;明文 HTTP 仅限 [uri]::IsLoopback | 机密(M3) |
| 非 GET 请求走 ShouldProcess;GET 总是执行 | 可预演的变更(M6) |
| 云数据源:先检查模块和登录状态,不满足则警告并跳过;绝不提示输入 | 上下文与凭据(M4、M5);非交互作业(第 1 课) |
统一的对象类型,带 Key(env/name) | 整形与比较(M7);综合实验按它做连接 |
How:错误约定
最终失败时,Invoke-OpsApi 抛出一个终止性错误,错误 ID 为 OpsApi.Http<status>(例如 OpsApi.Http401;网络错误为 OpsApi.Http0),消息为 <METHOD> <url> failed after N attempt(s): <API message>。调用方可以 catch 它,日志会说明是什么、在哪里、试了几次——凌晨 3 点排障时最需要的三件事。
When:何时用 Invoke-OpsApi,何时用 Az/AWS cmdlet
Azure 和 AWS 请使用厂商模块(它们为自己的 API 处理认证、重试和分页)。你自己的以及第三方的 REST API(CMDB、工单、监控、本课的模拟 API)使用 Invoke-OpsApi。对于还没有对应 cmdlet 的 ARM 端点,Invoke-AzRestMethod 可以复用 Az 上下文。
$null”——调用方无法区分“空”和“坏了”;失败就抛出。② “一直重试,总会恢复的”——要限制尝试次数和总时长。③ “令牌可以作为参数传入”——[string]$Token 参数最终会出现在历史记录和日志里;应在函数内部读取。④ “脚本上的 -Verbose 会显示重试”——除非显式传递,否则进不了模块内部(M6);综合实验中做了传递。⑤ “悄悄跳过 Azure 更友好”——要给出警告,让空的数据源可见。Invoke-OpsApi 内部流程
Invoke-OpsApi 流程
下面每个场景都是“命令”标签页或综合实验中的一次真实运行。动画下方是交互式排错树。
交互式排错树:我的 API / 云自动化失败了
命令表
| 命令 | 用途 |
|---|---|
Invoke-OpsApi /api/secure/servers -All | 获取分页端点的全部项 |
Invoke-OpsApi $p -Method Put -Body $o [-WhatIf] | 可预演的写操作 |
Invoke-OpsApi $p -Method Post -Body $o -RetryNonIdempotent | 有意重试创建操作(服务端保证幂等) |
Invoke-OpsApi $p -NoAuth -MaxRetries 2 -TimeoutSec 5 | 公开端点,紧凑的时间预算 |
$env:OPSKIT_API_URL / $env:OPSKIT_API_TOKEN | 指向另一个 API / CI 令牌 |
Get-OpsCloudInventory [-Source Local,Api,Azure,Aws] [-Env prod] | 合并后的清单 |
Update-PSModuleManifest -Path … -ModuleVersion 0.5.0 -FunctionsToExport … | 提升模块版本 |
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. 提升到 0.5.0 并加载
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
如果你的模块里有 v0.3/v0.4 的其余函数(Invoke-OpsBackup、Invoke-OpsHealthCheck),也要加入 -FunctionsToExport——FunctionsToExport 会替换整个列表。
2–3. 令牌处理与分页
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' # 实验值;在 CI 中它来自机密存储
$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. 瞬时故障与限流
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. 永久性错误、放弃重试,以及预演写操作
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. 统一的对象模型
$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. 在没有 Az / AWS.Tools 的机器上使用云数据源
$env:PSModulePath = Join-Path $PSHOME 'Modules' # 模拟一台裸机(仅当前会话) 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
# 安装了 Az 和 AWS.Tools 并登录沙盒后: Get-OpsCloudInventory -Source Local, Api, Azure, Aws | Group-Object Source -NoElement
Count Name
----- ----
12 Local
12 Api
4 Azure
3 Aws
如何验证:模拟 API 的 /stats 计数器必须与详细日志中的尝试次数一致;当 Local 与 Api 一致时,$inv | Group-Object Key | Where-Object Count -ne 2 为空(已验证:0 组)。常见错误:忘记把新函数名加入 FunctionsToExport——文件被加载了,命令却“无法识别”。生产用途:第 8 课会添加 Pester 测试,模拟 Invoke-RestMethod 返回 503/429/404 序列,并断言尝试次数和等待时间;另外加入 PSScriptAnalyzer,以及一个从机密设置 OPSKIT_API_TOKEN 的 CI 工作流。
目标:发布 OpsKit v0.5,并针对模拟 API 证明它的行为。环境:OpsKit v0.4,模拟 API 正在运行。费用:无。
~/pslab/OpsKit/Private/Get-OpsApiToken.ps1、~/pslab/OpsKit/Public/Invoke-OpsApi.ps1、~/pslab/OpsKit/Public/Get-OpsCloudInventory.ps1。Get-Module OpsKit 必须显示 0.5.0。Invoke-OpsApi /api/secure/servers -Verbose——第一行详细输出必须是 “SecretManagement secret 'OpsKitApiToken'”。Invoke-OpsApi '/flaky?key=lab8&fail=3' -NoAuth。预期:约 0.5 + 1 + 2 = 3.5 秒,在第 4 次尝试成功(实测:3.7 秒,第 4 次)。再加 -MaxRetries 2:3 次尝试后失败。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
-Drift 启动模拟 API(先停止旧实例),用 Group-Object Key 和 IP 比较找出两处差异——这就是综合实验的起点。Remove-Item Env:OPSKIT_API_TOKEN。案例 1:掩盖了一次故障的封装函数
问题:一个自研的 Invoke-Api 遇到任何错误都返回 $null。CMDB 宕机期间,夜间同步看到“没有服务器”,把 600 台服务器标记为已下线。根因:错误被转换成了空结果。修复:失败就抛出(像 Invoke-OpsApi 那样),由调用方决定;再加一项合理性检查(“如果数据源返回的数量不到昨天的 50%,拒绝同步”)。
案例 2:成倍放大负载的重试
问题:三层各自重试 3 次——HTTP 封装、使用它的函数、以及调度器——于是一次失败的调用变成了 27 个请求。根因:每一层都在重试。修复:只在一个地方(客户端)重试,并设置总时间预算;上层快速失败并报告。
案例 3:一份清单,四个“真相”
问题:CMDB、Azure、AWS 和监控工具对哪些服务器存在各执一词;每个团队都只相信自己的导出。根因:没有统一的键或对象模型。修复:从每个数据源生成规范化对象(Key、Source、State、Id),再做连接和漂移报表——正是 Get-OpsCloudInventory 加上综合实验的同步脚本。
常见错误与修复
Invoke-OpsApi: The term 'Invoke-OpsApi' is not recognized
原因:不在 FunctionsToExport 中,或先加载了旧版本的 OpsKit。修复:Get-Module OpsKit -ListAvailable;Import-Module ~/pslab/OpsKit -Force;检查清单。
failed after 1 attempt(s): HTTP 401
原因:没有找到令牌或令牌错误。修复:Invoke-OpsApi … -Verbose 会显示令牌的来源;检查 $env:OPSKIT_API_TOKEN 或 Get-SecretInfo OpsKitApiToken。
OpsApi.Http0 … No connection could be made
原因:API 未运行 / $env:OPSKIT_API_URL 错误。状态 0 表示根本没有收到 HTTP 响应。修复:启动模拟 API(模块 0);在 Windows 上用 Test-NetConnection 127.0.0.1 -Port 5050 检查。
WARNING: Azure source skipped: no Az context
修复:调用前在同一会话中执行 Connect-AzAccount(以及 Set-AzContext);在 CI 中,登录步骤必须在同一个作业中运行,并设置 enable-AzPSSession: true。
脚本加了 -Verbose 却看不到重试
原因:首选项变量不会传入模块(模块 6)。修复:调用 OpsKit 时传入 -Verbose:($VerbosePreference -eq 'Continue')。
1. 用 OpsKit 通过 API 获取所有 prod 服务器,只按名称排序输出名称。
Invoke-OpsApi '/api/secure/servers?env=prod&pageSize=2' -All | Sort-Object Name | ForEach-Object Name
2. 找出 Local 与 Api 之间 IP 不一致的服务器。
Get-OpsCloudInventory | Group-Object Key | Where-Object { @($_.Group.IP | Select-Object -Unique).Count -gt 1 } |
ForEach-Object Name一位同事提议给 Invoke-OpsApi 加一个 [string]$Token 参数,“为了灵活”。请回应。
字符串参数会诱使人在命令行上写字面量(进入历史文件,模块 3);如果有人记录绑定的参数,它会出现在 -Verbose/脚本记录中;令牌也会扩散到各个调用点。如果确实需要灵活性,可以接受 [securestring] 或机密名称(-SecretName),并把解析逻辑保留在 Get-OpsApiToken 中;CI 设置 OPSKIT_API_TOKEN。第 8 课会加入 PSScriptAnalyzer 来捕获明文凭据参数(例如针对类似密码名称的 PSAvoidUsingPlainTextForPassword)——但不要指望靠 linter 捕获所有令牌参数。
已验证的教学视频
没有找到演示构建一个类似 OpsKit 的、带重试和分页的 REST 客户端模块的已验证视频;以本模块的代码和运行结果为准。
官方文档
视频分镜(约 90 秒)
本教材无法直接生成视频或 MP3;分镜与旁白可交给视频工具使用。
画面:OpsKit 盒子打开,三个新文件滑入;版本标签从 0.4 翻到 0.5。
旁白:一个客户端对接所有 API,一份清单汇总所有数据源。
画面:流程图逐一点亮:令牌、环回检查、发送、分类、等待、下一页。
旁白:安全的令牌、只重试瞬时故障、遵守 Retry-After、分页、写操作可预演。
画面:Local 与 Api 的行按 env/name 交错在同一张表中;Azure 和 AWS 徽标显示“已跳过”警告。
旁白:同一个对象,任意数据源;缺失的数据源给出警告,而不是被隐藏。
画面:一行红色错误 “failed after 3 attempt(s): HTTP 503”。
旁白:失败时,它会说明是什么、在哪里、试了几次。
命令速查表
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) # 绝不使用默认深度 2 -StatusCodeVariable sc -ResponseHeadersVariable h $h['Location'][0] # 响应头的值是 String[]
2. HTTP 错误
try { Invoke-RestMethod $uri } # 4xx/5xx = 终止性错误
catch {
[int]$_.Exception.Response.StatusCode
($_.ErrorDetails.Message | ConvertFrom-Json).error.message
}
$b = Invoke-RestMethod $uri -SkipHttpErrorCheck -StatusCodeVariable sc
# -ErrorAction SilentlyContinue 并不能隐藏 HTTP 错误3. 分页、重试、超时
(Invoke-RestMethod $uri -FollowRelLink).value # Link: rel="next"
$all = while ($u) { $r = irm $u; $r.value; $u = $r.nextLink }
-MaximumRetryCount 3 -RetryIntervalSec 2 # 重试所有 >=400(包括 404、POST!)
# 429 遵循 Retry-After;超时/连接被拒不重试
-TimeoutSec 30 # = -ConnectionTimeoutSeconds(直到收到响应头)
-OperationTimeoutSeconds 30 # 读取响应体时的停顿4. 令牌与机密
$t = ConvertTo-SecureString $env:API_TOKEN -AsPlainText -Force Invoke-RestMethod $uri -Authentication Bearer -Token $t # 仅限 https # -AllowUnencryptedAuthentication → 仅用于本机回环实验 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) # 会写入历史文件吗?
5. Az
Disable-AzContextAutosave -Scope Process
Connect-AzAccount -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 # 守卫检查!
Get-AzResourceGroup -Tag @{owner='x'}; Get-AzVM -Status
New-AzResourceGroup … -WhatIf; az … --output json | ConvertFrom-Json6. AWS.Tools
Install-AWSToolsModule EC2, S3, SecurityToken -Cleanup
aws sso login --profile p; Set-AWSCredential -ProfileName p
Set-DefaultAWSRegion -Region ca-central-1 # 或每次调用时传 -Region
Get-STSCallerIdentity # 我是谁?
(Get-EC2Instance -Filter @{Name='tag:env';Values='prod'}).Instances
Get-EC2Instance -Select '*' / -NoAutoIteration -NextToken $t
Get-S3Bucket7. 幂等变更与数据整形
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 # 不要用 @($none.List).Count(空集合 → 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
综合实验 + 结业测验
~/pslab/scripts/Sync-OpsInventory.ps1:在 API 注入 503 与 429 故障且已发生漂移的情况下,让清单 API 与 inventory.json 保持一致——用 -WhatIf 预演、带重试地应用、证明幂等性,并返回调度器可据以行动的退出码场景
“云”(模拟 API)已经与事实来源发生漂移:prod/bastion-01 缺失,dev/db-01 的 IP 不对。每第三个经过认证的请求会失败(503 与 429 交替出现)。编写一个同步脚本:用 OpsKit 读取两侧数据;为每台服务器规划 Create、Update 或 Unmanaged;用 -WhatIf 预演;通过 Invoke-OpsApi 应用变更;即使在 -WhatIf 模式下也写出 JSON 报表;已同步时退出码为 0,仍有漂移时为 1,无法读取 API 时为 2。
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~/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
注意这里处理了三个已验证的陷阱:-WhatIf 也会跳过报表的 Set-Content(因此使用 -WhatIf:$false);-Verbose 不会传入 OpsKit(因此使用 @vb);由于脚本已经调用过 ShouldProcess,对模块函数的调用都带 -Confirm:$false。
./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
./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
第 2 页上的 429 和 PUT 上的 503 都被 Invoke-OpsApi 消化了;POST 之所以允许重试,是因为脚本传了 -RetryNonIdempotent——在这里是安全的,因为对已存在的服务器 API 会返回 409,不可能创建出重复项。
./scripts/Sync-OpsInventory.ps1; "exit=$LASTEXITCODE" # 无事可做
# 有人在事实来源之外手工创建了一台服务器
$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" # 故障不再被消化
$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
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
子 pwsh 从环境中继承了 OPSKIT_API_TOKEN——这正是 CI 中的用法。退出码 1 是正确的:prod/web-09 仍需人工决定。本次会话中共有九次注入的故障打到客户端,每一次要么被重试成功,要么以退出码 2 报告出来。
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
开放式自检
1. 为什么脚本要在做任何变更之前完整读取两侧数据?
这样读取失败(退出码 2)永远不会留下只应用了一半的同步,并且计划(以及 -WhatIf 输出)是完整、可审阅的。它还避免了在一个分页列表上交替读写——写操作会让列表的分页发生偏移。
2. 事故期间 API 开始返回 200 和一个空列表。会发生什么?你如何防范?
每台本地服务器都会被规划为 Create——API 会对每一台返回 409,结果为 Failed,退出码 1。如果同步具备删除能力,后果会严重得多。防范办法是设置合理性阈值:如果远端数量低于本地数量(或上一次报表数量)的某个比例,比如 50%,就以退出码 2 中止。
3. 如何从 GitHub Actions 每晚对真实 API 运行它?
一个定时工作流,shell: pwsh,从你的源安装 OpsKit(第 4 课),OPSKIT_API_URL 作为变量,OPSKIT_API_TOKEN 来自环境机密(或通过联合令牌交换获得)。每晚以 -WhatIf 运行,并把 JSON 报表作为构件上传;只在需要审批的受保护环境中运行应用模式。退出码 1 自动开 issue,退出码 2 呼叫值班人员。
4. 如果清单存放在 Azure 而不是模拟 API 中,今天课程的哪些部分会改变?
Api 数据源变成 Resource Graph(读取)加上带 -WhatIf 的 Update-AzTag / New-Az…(写入);认证变成托管标识或 OIDC,并加上显式的 Set-AzContext 守卫检查;ARM 的重试由 Az 处理,但限流仍然要求用一次 Resource Graph 查询代替大量调用。计划 / ShouldProcess / 报表 / 退出码这一结构保持不变。
来源与版本说明
| 主题 | 验证结果 | 来源(访问于 2026-11-24) |
|---|---|---|
| 7.6 上的 Web cmdlet | 在 7.6.10 上读取的 Invoke-RestMethod/Invoke-WebRequest 参数列表:-ConnectionTimeoutSeconds(别名 -TimeoutSec)、-OperationTimeoutSeconds、-MaximumRetryCount、-RetryIntervalSec、-FollowRelLink、-SkipHttpErrorCheck、-StatusCodeVariable、-ResponseHeadersVariable、-UnixSocket。7.4 的文档已列出这两个超时参数 | Invoke-RestMethod;Invoke-WebRequest;本课的实际运行 |
| HTTP 错误行为 | 4xx/5xx → HttpResponseException,属于语句终止性错误;-ErrorAction SilentlyContinue/Ignore 无法隐藏它;ErrorDetails.Message 保存(格式化后的)JSON 正文;调用抛出异常时 -StatusCodeVariable 保持为空 | 本课的实际运行(模块 1) |
| 内置重试 | 会重试 404 和 POST,429 时遵循 Retry-After(等待了 3 秒而非 1 秒),不重试超时和连接被拒;-OperationTimeoutSeconds 1 没有中断首字节耗时 3 秒的响应 | 本课的实际运行(模块 2);RFC 9110 Retry-After |
| ConvertTo-Json | 默认深度 2;截断警告;7.6 上 ConvertFrom-Json -AsHashtable 返回 OrderedHashtable | ConvertTo-Json;实际运行 |
| 机密 | SecretManagement 1.1.2 与 SecretStore 1.0.6 的命令列表、语法和枚举值(Authenticate:None、Password;Interaction:None、Prompt;Scope:CurrentUser、AllUsers),读取自保存到临时目录的模块;复现了 PSReadLine 2.4.5 历史处理器的判定 | SecretManagement;SecretStore;在自动化中使用机密 |
| Az PowerShell | Az 16.0.0 汇总模块(清单中含 102 个模块)、Az.Accounts 5.5.0 中 Connect-AzAccount 的参数集、Az.Resources 10.0.0 / Az.Compute 11.6.0 cmdlet 的 ShouldProcess/ConfirmImpact、Search-AzGraph(Az.ResourceGraph 1.3.0):-First 取值 1–1000,响应类型 PSResourceGraphResponse,含 SkipToken 和 Data——均读取自已安装模块的元数据 | 安装;Connect-AzAccount;上下文持久化;Search-AzGraph;Resource Graph |
| OIDC / 托管标识 | GitHub Actions 的联合凭据;非交互式登录选项 | GitHub Actions 通过 OIDC 连接 Azure;非交互式登录 |
| AWS.Tools | AWS.Tools 5.0.344 / Installer 2.0.6 元数据(EC2 共 843 个命令,S3 共 112 个,Get-EC2Instance 输出 Reservation,-Select 帮助文本,Get-AWSRegion 共 45 个区域,自动翻页模式 standard);V5 的变化(自动翻页、可空类型、移除 -PassThru、凭据环境变量、错误文本)以及 AWS 文档中的凭据搜索顺序 | 入门;迁移到 V5;凭据解析;区域 |
| 首选项变量传递 | 脚本的 -WhatIf/-Verbose 没有传入模块函数(变更被实际执行),但传入了脚本内定义的函数——已在 7.6.10 上复现 | about_Preference_Variables;实际运行(模块 6) |
| 限流 | ARM 请求限制与 429 处理 | ARM 限流 |
| 模拟 API 与 OpsKit | Start-MockApi.ps1、Set-LabServerTag、OpsKit v0.5 和 Sync-OpsInventory.ps1 与页面所印完全一致,并在 7.6.10 上运行(Windows、线程作业、127.0.0.1:5050) | 本课的实际运行 |
视频验证说明
本课只列出于 2026-11-24 通过 YouTube oEmbed(https://www.youtube.com/oembed?url=…&format=json)核实过标题和频道的视频:
- Call REST APIs with Invoke-RestMethod in PowerShell — Adam Driscoll(模块 1、2、8)
- PowerShell Quick Tips : Invoke-RestMethod vs Invoke-WebRequest (Calling Rest APIs) — JackedProgrammer(模块 1)
- New PowerShell Secrets Management Module - Easily use any secret provider — John Savill's Technical Training(模块 3)
- SecretManagement - Sydney Smith - PSConfEU 2022 — PowerShell Conference Europe(模块 3)
- How to Manage Secrets securely in PowerShell | Azure Key Vault — T-Minus365(模块 3)
- Getting Started with Azure PowerShell — John Savill's Technical Training(模块 4)
- AWS for Microsoft Workloads: Installing the AWS Tools for PowerShell — Amazon Web Services(模块 5)
- Automating AWS with PowerShell: A Practical Guide — RTPSUG April 2026 — Research Triangle PowerShell Users Group(模块 5)
- PowerShell Master Class - Automation — John Savill's Technical Training(模块 6、8)
- How to use PowerShell Try, Catch and the Write-Verbose and Write-Debug — John Savill's Technical Training(模块 6)
- PowerShell Master Class - Data and Objects — John Savill's Technical Training(模块 7)
- Get Familiar with Microsoft Azure Resource Graph — Tim Warner(模块 7)
oEmbed 只能核实标题和频道;这些视频没有逐段观看,“meta” 说明来自标题和公开信息。其中若干视频早于 PowerShell 7.6、Az 16 或 AWS.Tools V5;行为有差异时以本课为准。搜索找到的两个候选视频因 oEmbed 未返回元数据而被排除。以下主题未找到经过验证的视频:7.x 的确切重试规则与超时参数、PSReadLine 的历史过滤、首选项变量向模块的传递、构建带重试的 REST 客户端模块。
语音朗读说明
“语音”页使用浏览器内置的 Web Speech API 朗读讲解稿(zh-CN);无需网络访问或外部脚本。课件无法嵌入 MP3 文件或生成视频;讲解稿和分镜可以交给 TTS 或视频工具使用。
已知限制
- 没有进行任何云登录。
Connect-AzAccount、Get-AzContext、Get-AzResourceGroup、Get-AzVM、New-/Remove-AzResourceGroup -WhatIf、Update-AzTag、Search-AzGraph查询结果、Get-STSCallerIdentity、Get-EC2Instance、Get-S3Bucket、AWS 凭据错误以及四个数据源的Get-OpsCloudInventory运行的全部输出均为预期输出,其中的 ID、名称和数量仅为示意。Az/AWS cmdlet 的元数据(参数集、ShouldProcess、输出类型、帮助文本、区域列表)是真实的。 - 没有运行 SecretManagement 保管库操作(为避免改动用户配置,实验机上未执行
Register-SecretVault、Set-Secret、Set-SecretStoreConfiguration或Unlock-SecretStore)。它们的输出以及 “no extension vaults registered” 消息均为预期输出;命令列表、语法和枚举值是真实的。 - 所示的 Azure CLI 调用(
az version)是本地调用;其行数取决于已安装的扩展。 - 运行环境:Windows 11、PowerShell 7.6.10、.NET 10.0.15;模拟 API 以线程作业方式运行。在实验机上,127.0.0.1 上的
HttpListener无需管理员权限即可工作;未在 Linux 和 macOS 上测试。路径已替换为C:\Users\labadmin\…。 - 耗时数据(2.0 秒、3.0 秒、3.7 秒)来自空闲机器上的一次运行,可能略有差异。综合实验中注入的故障落在哪个请求上,取决于此前的请求数量。
- 部分错误显示被缩短为第一行或仅保留错误消息(“错误视图已缩短”)。
- 动画做了简化:省略了 TLS、代理、重定向、HTTP/2 协商、抖动,以及 MSAL 和 AWS SDK 凭据提供程序的内部细节。