发送 HTTP 请求,返回状态码、响应头和内容,可下载文件。
Invoke-WebRequest 返回 BasicHtmlWebResponseObject,包含 StatusCode、StatusDescription、Headers、Content、RawContent、Links、Forms 等;别名是 iwr,5.1 还有 curl、wget。-Body 可按值接收管道输入,但请求地址、方法和内容类型仍要显式给出;响应对象可以继续 Select-Object 或解析。
权限:普通用户即可发起网络请求,受代理、防火墙和 TLS 策略限制;访问需要认证的资源用 -Credential 或 -Headers,不要把令牌硬编码在脚本里。边界:它处理 HTTP 层,不自动解析 JSON(用 Invoke-RestMethod 更省事);提交 JSON 时必须 ConvertTo-Json 并设置 ContentType。
版本:5.1 默认使用 Internet Explorer 解析引擎,Server Core 或未安装 IE 的环境会失败,通常要加 -UseBasicParsing;7.x 差异:始终使用基本解析,-UseBasicParsing 仅为兼容而保留,curl/wget 别名已移除,调用原生工具要写 curl.exe。
# 1. 获取页面并查看状态码和内容长度
PS C:\> $r = Invoke-WebRequest -Uri 'https://learn.microsoft.com' -UseBasicParsing; $r.StatusCode; $r.Content.Length
# 2. 下载文件到本地,-OutFile 不返回响应对象
PS C:\> Invoke-WebRequest -Uri 'https://example.com/files/report.zip' -OutFile C:\Temp\report.zip
# 3. 提交 JSON;先序列化,再设置 Content-Type
PS C:\> $body = @{ name='api'; port=8080 } | ConvertTo-Json; Invoke-WebRequest -Uri 'https://api.example.com/apps' -Method Post -Body $body -ContentType 'application/json' -UseBasicParsing
# 4. 捕获 404 等 HTTP 错误,读取状态码而不是只看红字
PS C:\> try { Invoke-WebRequest -Uri 'https://example.com/missing' -UseBasicParsing -ErrorAction Stop } catch { $_.Exception.Response.StatusCode.value__ }
# 5. 添加请求头和超时,模拟客户端并防止长时间挂起
PS C:\> Invoke-WebRequest -Uri 'https://example.com' -Headers @{ 'User-Agent'='cmd-hub' } -TimeoutSec 10 -UseBasicParsing | Select-Object StatusCode
# 6. 用会话变量保存 Cookie,再访问需要登录的页面
PS C:\> Invoke-WebRequest -Uri 'https://example.com/login' -Method Post -Body @{ user='demo' } -SessionVariable s -UseBasicParsing
PS C:\> Invoke-WebRequest -Uri 'https://example.com/profile' -WebSession $s -UseBasicParsing | Select-Object StatusCode
-UseBasicParsing;它返回基本响应对象,Links/Forms 不再可用,需要 DOM 解析应换用专门库。try/catch 并读 $_.Exception.Response;不要只看 $r.StatusCode,因为请求失败时没有正常返回值。[Net.ServicePointManager]::SecurityProtocol,按系统支持启用 TLS 1.2,而不是关闭证书校验。-Body 传哈希表会按表单编码发送,不是 JSON;JSON API 要 ConvertTo-Json 并设置 application/json。-OutFile 成功时没有响应对象,后续 .StatusCode 为空;需要响应就分开请求,或 7.x 用 -PassThru 保留对象。-MaximumRedirection 0,但要注意它会把重定向当成错误抛出。curl/wget 是别名而不是原生程序,参数不兼容;要原生行为写 curl.exe,7.x 中别名已移除。Invoke-RestMethod — 直接反序列化 JSON/XML API 响应。curl — 命令行 HTTP 客户端,参数与别名不同。PowerShell — 了解 5.1/7.x 的解析引擎和别名差异。ConvertTo-Json — 构造 JSON 请求体。合上页面,先回答,再展开对照。
$r.StatusCode 为什么拿不到?应该读哪里?-Body 会发送什么格式?-UseBasicParsing,或改用 7.x。catch 中读 $_.Exception.Response。application/x-www-form-urlencoded)编码;应 ConvertTo-Json 并设置 -ContentType 'application/json'。
小程序版
微信扫码,随时查命令