#网络请求
PowerShell 进行 HTTP 请求主要使用两个命令:Invoke-WebRequest 返回完整的响应对象,Invoke-RestMethod 则直接把响应内容转换为对象。二者在 PowerShell 7 中均跨平台可用。
#Invoke-WebRequest
基本语法:
Invoke-WebRequest -Uri <地址> [-Method <方法>] [-Headers <表头>] [-Body <正文>] [-ContentType <类型>]
发送 GET 请求并查看响应:
> $resp = Invoke-WebRequest -Uri 'https://api.github.com/repos/PowerShell/PowerShell'
> $resp.StatusCode
> ($resp.Content | ConvertFrom-Json).stargazers_count
Invoke-WebRequest 返回的对象包含 StatusCode、Headers、Content 等属性,适合需要查看状态码或原始内容的场景。
#Invoke-RestMethod
Invoke-RestMethod 会自动把 JSON 或 XML 响应转换为 PowerShell 对象:
> $repo = Invoke-RestMethod -Uri 'https://api.github.com/repos/PowerShell/PowerShell'
> $repo.full_name
大多数 REST API 的调用都可以写成:
> $result = Invoke-RestMethod -Uri 'https://api.example.com/items' `
-Method Get `
-Headers @{ Accept = 'application/json' }
#请求方法与数据
-Method 可取 Get、Post、Put、Patch、Delete 等值。发送 JSON 数据时,先用 ConvertTo-Json 生成正文:
> $body = @{ name = 'demo'; value = 1 } | ConvertTo-Json
> $result = Invoke-RestMethod -Uri 'https://api.example.com/items' `
-Method Post `
-Body $body `
-ContentType 'application/json'
-Headers使用哈希表传递自定义表头,例如认证令牌。-Body可以是字符串、字节数组或哈希表;发送 JSON 时通常传入字符串。-ContentType必须与正文格式一致,否则服务器可能拒绝请求。
携带令牌的示例:
> $headers = @{ Authorization = "Bearer $env:API_TOKEN" }
> Invoke-RestMethod -Uri 'https://api.example.com/me' -Headers $headers
#处理 JSON API
典型的 JSON API 调用流程是:请求、检查状态、读取字段。
> try {
$data = Invoke-RestMethod -Uri 'https://api.example.com/items' -ErrorAction Stop
$data | Select-Object -First 3
} catch {
Write-Warning "请求失败:$($_.Exception.Message)"
}
如果响应不是对象而是数组,Invoke-RestMethod 会返回数组,可以直接用管道处理。
#TLS 与代理
PowerShell 7 使用 .NET 的默认 TLS 设置,通常会自动协商较新的协议。若需显式指定代理,可使用:
> Invoke-RestMethod -Uri 'https://api.example.com/items' `
-Proxy 'http://proxy.example.com:8080' `
-ProxyCredential (Get-Credential)
-Proxy指定代理服务器地址。-ProxyCredential提供代理认证凭据。-TimeoutSec设置超时时间,避免请求长时间挂起。- 在开发或测试环境中,PowerShell 6 及以上可用
-SkipCertificateCheck跳过证书校验。