iwr命令,全称为Invoke-WebRequest,是PowerShell中一个功能强大的 cmdlet(命令行工具),用于从Web服务器获取数据、提交表单、下载文件等操作,它类似于其他命令行环境中的curl或wget命令,但集成了PowerShell的强大功能,能够处理复杂的HTTP请求、解析响应内容,并与PowerShell的对象处理能力无缝结合,无论是简单的网页抓取、API调用,还是需要处理身份验证、自定义请求头的复杂场景,iwr命令都能胜任,以下将从基本语法、核心功能、高级用法及实际应用场景等方面详细介绍iwr命令的使用方法。

iwr命令的基本语法与核心参数
iwr命令的基本语法结构为:Invoke-WebRequest [-Uri] <Uri> [-Method <WebRequestMethod>] [-Body <Object>] [-Headers <IDictionary>] [-ContentType <String>] [-Credential <PSCredential>] [-TimeoutSec <Int32>] [-UserAgent <String>] [-Proxy <Uri>] [-ProxyCredential <PSCredential>] [-SessionVariable <String>] [-UseBasicParsing] [-OutFile <String>] [-ErrorAction <ActionPreference>]
,以下是其核心参数的详细说明:
参数名 | 作用 | 示例 |
---|---|---|
Uri | 指定请求的目标URL,必须为绝对URI(以http://或https://开头) | iwr -Uri "https://example.com/api/data" |
Method | 指定HTTP请求方法,如GET、POST、PUT、DELETE等,默认为GET | iwr -Uri "https://example.com/submit" -Method POST |
Body | 请求体的内容,用于POST/PUT请求,可以是字符串、哈希表或文件路径 | iwr -Uri "https://example.com/login" -Method POST -Body @{username="admin";password="123"} |
Headers | 自定义HTTP请求头,通过哈希表形式传递 | iwr -Uri "https://example.com/api" -Headers @{"Authorization"="Bearer token123"} |
ContentType | 指定请求体的内容类型,如application/json、text/html等 | iwr -Uri "https://example.com/api" -Body $json -ContentType "application/json" |
Credential | 指定身份验证凭据,支持用户名/密码或PSCredential对象 | iwr -Uri "https://example.com/secure" -Credential (Get-Credential) |
TimeoutSec | 设置请求超时时间(秒),默认为0(无限等待) | iwr -Uri "https://example.com/slow" -TimeoutSec 30 |
UserAgent | 自定义请求的User-Agent字符串,用于模拟浏览器或客户端 | iwr -Uri "https://example.com" -UserAgent "Mozilla/5.0 (Windows NT 10.0; Win64; x64)" |
OutFile | 保存到指定文件,支持下载文件或保存网页源码 | iwr -Uri "https://example.com/file.zip" -OutFile "C:\downloads\file.zip" |
UseBasicParsing | 禁用HTML/XML解析,直接返回原始响应内容,适用于非结构化数据或避免解析错误 | iwr -Uri "https://example.com/raw" -UseBasicParsing |
iwr命令的核心功能与使用场景
获取网页内容与解析HTML
iwr命令最常用的功能是获取网页的HTML源码,并通过PowerShell的对象模型解析内容,获取网页标题或提取特定元素:
# 获取网页HTML内容 $response = iwr -Uri "https://example.com" $response.Content | Out-File -FilePath "C:\webpage.html" # 保存完整HTML # 解析HTML标题(通过ParsedHtml属性) $title = $response.ParsedHtml.title Write-Output "网页标题: $title" # 提取所有链接(通过getElementsByTagName方法) $links = $response.ParsedHtml.getElementsByTagName("a") foreach ($link in $links) { Write-Output "链接文本: $($link.innerText) - URL: $($link.href)" }
需要注意的是,ParsedHtml
依赖于Windows的HTML解析引擎,若目标网页结构复杂或包含动态加载的内容,可能需要结合-UseBasicParsing
参数或使用其他工具(如Invoke-RestMethod)。
调用RESTful API与处理JSON数据
iwr命令是调用REST API的利器,支持发送JSON格式的请求体并解析响应中的JSON数据,调用一个获取用户信息的API:

# 定义API端点和请求体 $apiUri = "https://api.example.com/users/1" $jsonBody = @{name="John";age=30} | ConvertTo-Json # 发送POST请求并获取JSON响应 $response = iwr -Uri $apiUri -Method POST -Body $jsonBody -ContentType "application/json" $userData = $response.Content | ConvertFrom-Json # 输解析后的数据 Write-Output "用户名: $($userData.name)" Write-Output "年龄: $($userData.age)"
对于需要身份验证的API,可通过-Headers
参数传递Token或-Credential
参数传递基本认证凭据。
文件下载与断点续传
iwr命令支持直接下载文件,并通过-OutFile
参数指定保存路径,对于大文件,可通过-Headers
参数实现断点续传:
# 下载文件 $downloadUri = "https://example.com/largefile.zip" $outputPath = "C:\downloads\largefile.zip" # 获取文件大小以支持断点续传 $fileInfo = iwr -Uri $downloadUri -Method HEAD $fileSize = $fileInfo.Headers['Content-Length'] $range = "bytes=0-$($fileSize-1)" # 分块下载(示例:分3块下载) $chunkSize = [math]::Round($fileSize / 3) for ($i = 0; $i -lt 3; $i++) { $start = $i * $chunkSize $end = if ($i -eq 2) {$fileSize-1} else {($i+1) * $chunkSize - 1} $range = "bytes=$start-$end" $response = iwr -Uri $downloadUri -Headers @{"Range"=$range} -OutFile "$outputPath.part$i" } # 合并文件(示例:简单拼接,实际需根据分块规则处理) Get-Content "$outputPath.part0" -Raw | Set-Content $outputPath Get-Content "$outputPath.part1" -Raw | Add-Content $outputPath Get-Content "$outputPath.part2" -Raw | Add-Content $outputPath # 清理临时文件 Remove-Item "$outputPath.part0", "$outputPath.part1", "$outputPath.part2"
实际应用中,断点续传需更复杂的逻辑(如检查已下载块),但上述示例展示了基本原理。
处理表单提交与Cookie
iwr命令可模拟浏览器提交表单,并自动处理Cookie(通过-SessionVariable
参数保存会话状态),登录一个网站并获取受保护资源:

# 登录并保存会话 $loginUri = "https://example.com/login" $loginData = @{username="admin";password="secret";submit="Login"} $response = iwr -Uri $loginUri -Method POST -Body $loginData -SessionVariable "session" # 使用保存的会话访问受保护页面 $protectedUri = "https://example.com/dashboard" $protectedResponse = iwr -Uri $protectedUri -WebSession $session Write-Output "受保护页面内容: $($protectedResponse.Content)"
-SessionVariable
会将Cookie和会话信息保存到指定变量中,后续请求通过-WebSession
参数复用,避免重复登录。
iwr命令的高级用法与注意事项
处理HTTPS与SSL证书
默认情况下,iwr命令会验证HTTPS证书的有效性,若目标网站使用自签名证书或证书链不完整,可通过-SkipCertificateCheck
参数(需PowerShell 6+)或修改系统信任设置绕过验证:
# 跳过SSL证书验证(不推荐用于生产环境) iwr -Uri "https://self-signed.example.com" -SkipCertificateCheck
代理服务器配置
通过-Proxy
和-ProxyCredential
参数,iwr命令可通过代理服务器发送请求:
# 使用代理服务器 $proxyUri = "http://proxy.example.com:8080" $response = iwr -Uri "https://example.com" -Proxy $proxyUri -ProxyCredential (Get-Credential)
异步请求与超时处理
对于长时间运行的请求,可通过-TimeoutSec
设置超时时间,避免无限等待:
# 设置30秒超时 $response = iwr -Uri "https://example.com/slow-api" -TimeoutSec 30 if ($response -eq $null) { Write-Output "请求超时" }
错误处理与调试
iwr命令可通过-ErrorAction
参数控制错误处理方式(如Stop
、Continue
),并通过$Error
变量捕获错误信息:
# 捕获请求错误 try { $response = iwr -Uri "https://example.com/not-found" -ErrorAction Stop } catch { Write-Output "请求失败: $($_.Exception.Message)" }
iwr命令的替代与选择
虽然iwr功能强大,但在某些场景下,其他命令可能更合适:
- Invoke-RestMethod:与iwr类似,但默认将响应内容解析为PowerShell对象(如JSON、XML),适合直接处理API数据,无需手动转换。
- curl(Windows 10+内置):轻量级HTTP客户端,语法简洁,适合简单请求,但功能不如iwr丰富。
- wget(通过Git for Windows或其他工具安装):传统命令行下载工具,专注于文件下载,不支持复杂的HTTP交互。
相关问答FAQs
Q1: iwr命令与Invoke-RestMethod有什么区别?如何选择?
A1: iwr(Invoke-WebRequest)和Invoke-RestMethod均用于HTTP请求,但核心区别在于响应处理方式:
- iwr返回包含HTTP头、状态码、原始内容的WebResponse对象,适合需要解析HTML、处理复杂响应或获取原始数据的场景。
- Invoke-RestMethod默认将响应内容解析为PowerShell对象(如JSON转为对象、XML转为XML元素),适合直接处理API返回的结构化数据,简化了后续操作。
选择建议:若需要解析HTML或获取完整HTTP响应,用iwr;若调用REST API并直接使用JSON/XML数据,用Invoke-RestMethod更便捷。
Q2: 使用iwr命令下载大文件时如何避免内存溢出?
A2: iwr默认将响应内容全部加载到内存中,若下载大文件(如GB级别),可能导致内存溢出,解决方法有两种:
- 使用
-OutFile
参数:直接将响应流写入文件,避免加载到内存,例如iwr -Uri "https://example.com/largefile.zip" -OutFile "C:\downloads\file.zip"
。 - 分块下载:通过
-Headers
参数设置Range请求头,分块下载文件并逐块写入临时文件,最后合并(如本文“断点续传”示例)。
-OutFile
是推荐方法,语法简单且性能最佳,适用于大多数文件下载场景。