约 2945 字

约 15 分钟

#PowerShell 的 Invoke-WebRequest 命令

Invoke-WebRequest
    [-Uri] <Uri>
    [-Method <WebRequestMethod>]
    [-Headers <IDictionary>]
    [-Body <Object>]
    [-ContentType <String>]
    [-WebSession <WebRequestSession>]
    [-SessionVariable <String>]
    [-Credential <PSCredential>]
    [-UseBasicParsing]
    [-SkipCertificateCheck]
    [-MaximumRedirection <Int32>]
    [-OutFile <String>]
    [-PassThru]
    [<CommonParameters>]

功能

向指定 URL 发送 HTTP 或 HTTPS 请求,并返回包含状态码、响应头和内容的响应对象。

类型

Cmdlet,属于 Microsoft.PowerShell.Utility。

参数

  • [-Uri] <Uri> - 请求的目标 URI;位置 0
  • -Method <WebRequestMethod> - HTTP 方法,如 Get、Post、Put、Delete、Patch
  • -Headers <IDictionary> - 请求头哈希表
  • -Body <Object> - 请求正文,可以是字符串、字节数组或哈希表
  • -ContentType <String> - 请求正文的 MIME 类型,如 application/json
  • -WebSession <WebRequestSession> - 使用已有的 Web 会话
  • -SessionVariable <String> - 将本次会话保存到指定变量
  • -Credential <PSCredential> - 用于身份验证的凭据
  • -UseBasicParsing - 在 PowerShell 6 及以上版本中已不再需要,保留用于兼容
  • -SkipCertificateCheck - 跳过 TLS 证书验证,仅应在可信环境中使用
  • -MaximumRedirection <Int32> - 最大重定向次数
  • -OutFile <String> - 将响应内容保存到文件
  • -PassThru - 与 -OutFile 一起使用时仍返回响应对象

#示例

发送 GET 请求

> $resp = Invoke-WebRequest -Uri 'https://api.github.com/repos/PowerShell/PowerShell'
> $resp.StatusCode
> $resp.Headers['Content-Type']
200
application/json; charset=utf-8
  • 响应对象包含 StatusCode、Headers、Content 等属性。

解析 JSON 响应

> $resp = Invoke-WebRequest -Uri 'https://api.github.com/repos/PowerShell/PowerShell'
> ($resp.Content | ConvertFrom-Json).stargazers_count
  • Content 是字符串,通常需要配合 ConvertFrom-Json 使用。

发送 POST 请求

> $body = @{ name = 'Alice' } | ConvertTo-Json
> Invoke-WebRequest -Uri 'https://httpbin.org/post' -Method Post -Body $body -ContentType 'application/json'
  • 发送 JSON 时需要同时设置 -ContentType 'application/json'。

添加自定义请求头

> $headers = @{ Authorization = 'Bearer <token>' }
> Invoke-WebRequest -Uri 'https://api.example.com/me' -Headers $headers
  • 请求头使用哈希表传入,键和值均为字符串。

下载文件

> Invoke-WebRequest -Uri 'https://example.com/file.zip' -OutFile './file.zip'
  • 指定 -OutFile 后内容会写入文件;需要同时获取响应对象时加 -PassThru。

保持会话

> Invoke-WebRequest -Uri 'https://example.com/login' -SessionVariable session
> Invoke-WebRequest -Uri 'https://example.com/profile' -WebSession $session
  • -SessionVariable 保存会话,后续请求用 -WebSession 复用登录状态。

#推荐阅读

更新: 2026/11/2

作者: planc

创建: 2026/11/2