#PowerShell 的 Invoke-RestMethod 命令
Invoke-RestMethod [-Uri] <Uri> [-Method <WebRequestMethod>]
[-Headers <IDictionary>] [-Body <Object>] [-ContentType <String>]
功能
向 HTTP 或 HTTPS API 发出请求。JSON 响应会反序列化为 PowerShell 值,可以直接读取属性。
类型
Cmdlet,属于 Microsoft.PowerShell.Utility。
参数
-Uri指定请求地址。-Method指定 HTTP 方法,默认发送 GET 请求。-Headers接收哈希表,用于设置 HTTP 请求头。-Body指定请求正文。发送 JSON 时,可用ConvertTo-Json生成正文,并将-ContentType设置为application/json。
#示例
读取公开的仓库信息
$repo = Invoke-RestMethod -Uri 'https://api.github.com/repos/PowerShell/PowerShell'
$repo.full_name
PowerShell/PowerShell
此例访问 GitHub 的公开 API,需要联网。未认证请求可能遇到限流。API 返回数组时,先把结果赋给变量,再将变量送入管道,可逐项处理数组元素。