PowerShell 5.1中Invoke-WebRequest使用-Form参数报错,需如何解决?
问题
在Windows 10系统的PowerShell 5.1中使用Invoke-WebRequest的-Form参数时,提示找不到匹配的参数名。本地查看Invoke-WebRequest帮助文档未发现-Form选项,但微软官方帮助文档的示例6中存在该选项。该工具用于下载文件时功能正常,相关脚本及错误信息如下:
脚本
$Uri = 'http://xxxxx.xxx.xxxx.xxx:8080/upload/upload.php' $Form = @{ file = Get-Item -Path 'C:\temp\xxxxxxx.pdf' nmbr = 'xxxxxxx' } Invoke-WebRequest -Uri $Uri -Method Post -Form $Form
错误信息
Invoke-WebRequest : A parameter cannot be found that matches parameter name 'Form'. At line:6 char:42 + Invoke-WebRequest -Uri $Uri -Method Post -Form $Form + ~~~~~ + CategoryInfo : InvalidArgument: (:) [Invoke-WebRequest], ParameterBindingException + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
解决方案
参数版本兼容性问题
-Form参数是PowerShell Core(6.0及以上版本)才新增的功能,而你使用的PowerShell 5.1属于Windows PowerShell,并不支持这个参数——这就是本地帮助文档没有该选项但官方文档示例存在的原因,官方文档通常默认展示最新PowerShell版本的内容。PowerShell 5.1替代实现方法
在PowerShell 5.1中,需要手动构建multipart/form-data格式的请求体来实现表单上传,示例如下:
$Uri = 'http://xxxxx.xxx.xxxx.xxx:8080/upload/upload.php' $filePath = 'C:\temp\xxxxxxx.pdf' $fileContent = [System.IO.File]::ReadAllBytes($filePath) $boundary = [System.Guid]::NewGuid().ToString() $LF = "`r`n" # 构建表单内容 $bodyLines = ( "--$boundary", "Content-Disposition: form-data; name=`"file`"; filename=`"$(Split-Path $filePath -Leaf)`"", "Content-Type: application/pdf$LF", [System.Text.Encoding]::ASCII.GetString($fileContent), "--$boundary", "Content-Disposition: form-data; name=`"nmbr`"$LF", "xxxxxxx", "--$boundary--$LF" ) -join $LF # 发送请求 Invoke-WebRequest -Uri $Uri -Method Post -ContentType "multipart/form-data; boundary=`"$boundary`"" -Body $bodyLines
- 长期解决方案
直接升级到PowerShell 7.x(最新的跨平台版本),升级后即可直接使用-Form参数,语法和你原本编写的脚本完全一致,无需修改代码。
内容的提问来源于stack exchange,提问作者DJK
相关产品推荐
相关产品推荐

