ZetCode

PowerShell Invoke-RestMethod

最后修改:2025 年 2 月 15 日

在本文中,我们将介绍 PowerShell 中的 Invoke-RestMethod cmdlet。此 cmdlet 向 RESTful Web 服务发送 HTTP/HTTPS 请求。它通过自动转换 JSON 响应来简化与 API 的交互。

REST 基础知识

REST(Representational State Transfer,表述性状态转移)是 Web 服务的一种架构风格。它使用标准的 HTTP 方法,如 GET、POST、PUT 和 DELETE。REST API 通常以 JSON 或 XML 格式返回数据。PowerShell 的 Invoke-RestMethod 可高效处理这些请求和响应。

基本 GET 请求

最简单的用法是发出 GET 请求以从 API 检索数据。-Uri 参数指定了端点 URL。默认情况下,响应会从 JSON 转换为 PowerShell 对象。这使得数据处理变得容易。

rest1.ps1
$response = Invoke-RestMethod -Uri "https://jsonplaceholder.typicode.com/posts/1"
$response

此命令从 JSONPlaceholder API 获取一个示例帖子。响应存储在 $response 变量中并显示。输出已自动解析。

带 JSON 主体的 POST 请求

要将数据发送到 API,请使用带 JSON 主体的 POST 请求。-Method 参数指定 POST。-Body 参数包含要发送的数据。对于 JSON 数据,Content-Type 标头应设置为 application/json。

rest2.ps1
$body = @{
    title = 'foo'
    body = 'bar'
    userId = 1
} | ConvertTo-Json

$response = Invoke-RestMethod -Uri "https://jsonplaceholder.typicode.com/posts" `
    -Method Post -Body $body -ContentType "application/json"
$response

此命令在模拟 API 上创建一个新帖子。哈希表被转换为 JSON 格式。响应包含创建的帖子,并分配了一个 ID。

PS C:\> .\rest2.ps1

title body userId id
----- ---- ------ --
foo   bar       1 101

处理身份验证

许多 API 都需要身份验证。-Headers 参数可以包含 API 密钥。对于基本身份验证,请使用 -Credential 参数。OAuth 令牌通常在标头中传递。请务必妥善保管凭据。

rest3.ps1
$headers = @{
    "Authorization" = "Bearer your_api_token_here"
    "Accept" = "application/json"
}

$response = Invoke-RestMethod -Uri "https://api.example.com/protected" `
    -Headers $headers
$response

此示例演示如何包含授权令牌。标头字典包含所需的身份验证。将令牌替换为您实际的 API 密钥。

错误处理

API 可能会返回需要正确处理的错误。使用 try/catch 块来优雅地管理错误。-StatusCodeVariable 参数捕获状态码。这有助于调试失败的请求。

rest4.ps1
try {
    $response = Invoke-RestMethod -Uri "https://jsonplaceholder.typicode.com/nonexistent" `
        -ErrorAction Stop -StatusCodeVariable statusCode
    $response
}
catch {
    Write-Host "Error: $($_.Exception.Message)"
    Write-Host "Status code: $statusCode"
}

此命令尝试访问一个不存在的端点。错误被捕获并显示。状态码已存储以供参考。在生产脚本中始终实现错误处理。

处理分页 API

许多 API 会对大型结果集进行分页。您需要处理多个请求。响应通常包含指向下一页的链接。此示例演示了如何处理多个页面的结果。

rest5.ps1
$baseUri = "https://api.example.com/items"
$allResults = @()
$nextPage = $baseUri

while ($nextPage) {
    $response = Invoke-RestMethod -Uri $nextPage
    $allResults += $response.items
    $nextPage = $response.links.next
}

$allResults | Select-Object -First 10

此脚本从分页 API 收集所有项目。它会跟踪下一页链接,直到没有为止。结果累积在 $allResults 数组中。为简洁起见,仅显示前 10 个项目。

来源

PowerShell 文档

在本文中,我们介绍了 PowerShell 中的 Invoke-RestMethod cmdlet。

作者

我叫 Jan Bodnar,是一名充满热情的程序员,拥有丰富的编程经验。我自 2007 年以来一直在撰写编程文章。至今,我已撰写了 1,400 多篇文章和 8 本电子书。我在教学编程方面拥有十多年的经验。

列出 所有 PowerShell 教程