PowerShell Invoke-RestMethod发送PUT请求时Body内容未正确传递
我用PowerShell脚本通过Invoke-RestMethod构建PUT请求更新Azure DevOps Wiki页面,代码如下:
# Main global var $securePassword = ConvertTo-SecureString -String $pat -AsPlainText $credential = [PSCredential]::new($username, $securePassword) $organization = "myorganization" $project = "myproject" $username = "username" $pat = "myRandomPatFromAzureDevOps" # AZDO build env var $buildNumber = "test1.0" # AZDO Wiki global vars $page = "Release-Notes-$buildNumber" $Body = [PsCustomObject]@{ "content" = "$results" } | ConvertTo-Json $headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" $headers.Add("Content-Type", "application/json") Invoke-RestMethod -Uri "https://dev.azure.com/$organization/$project/_apis/wiki/wikis/MyWiki.wiki/pages?path=$page&api-version=7.0" -Method 'PUT' -Authentication Basic -Credential $credential -Headers $headers -Body $Body
根据Azure DevOps REST API文档,更新Wiki需要在请求Body中传入字符串格式的content参数。我的$results是通过GET接口获取的Object[]类型数据,已经用ConvertTo-MarkDownTable函数转换成了Markdown表格字符串,但执行PUT请求后,返回结果显示content为空,内容没传过去;用Postman发送相同请求时,content能正常解析并更新Wiki页面。请问为什么PowerShell脚本里的PUT请求没法像Postman那样正确传递Body的content内容?
1. 修复变量定义顺序的致命错误
你的代码里$username和$pat是在创建$securePassword和$credential之后才定义的,这会导致$pat在执行ConvertTo-SecureString时是空值,生成的PSCredential无效。必须把$username和$pat的定义移到最前面:
# Main global var $username = "username" $pat = "myRandomPatFromAzureDevOps" $securePassword = ConvertTo-SecureString -String $pat -AsPlainText -Force $credential = [PSCredential]::new($username, $securePassword) $organization = "myorganization" $project = "myproject"
2. 确认$results的内容有效性
先验证$results确实是正确的Markdown字符串,避免源数据本身为空或格式异常:
# 输出到控制台查看 Write-Host "Results content:`n$results" # 写入文件,用编辑器打开确认格式 $results | Out-File -Path "test_markdown.md" -Encoding UTF8
打开生成的test_markdown.md,确保表格结构完整、内容正确。
3. 优化Body的构建与传递方式
手动转换JSON时容易出现转义或编码问题,推荐直接传递PSObject给Invoke-RestMethod,让它自动处理JSON序列化和请求头:
# 直接创建PSObject,无需手动转JSON $Body = [PsCustomObject]@{ content = $results } # 调用接口时无需手动添加Content-Type头,PowerShell会自动处理 Invoke-RestMethod -Uri "https://dev.azure.com/$organization/$project/_apis/wiki/wikis/MyWiki.wiki/pages?path=$page&api-version=7.0" ` -Method 'PUT' ` -Authentication Basic ` -Credential $credential ` -Body $Body
如果必须手动转换JSON,要确保转义正确并指定UTF-8编码:
$Body = [PsCustomObject]@{ content = $results } | ConvertTo-Json -Depth 10 -Compress Invoke-RestMethod -Uri "https://dev.azure.com/$organization/$project/_apis/wiki/wikis/MyWiki.wiki/pages?path=$page&api-version=7.0" ` -Method 'PUT' ` -Authentication Basic ` -Credential $credential ` -ContentType "application/json; charset=utf-8" ` -Body $Body
4. 处理页面路径的URL编码
如果$page包含特殊字符(比如空格、斜杠),需要对路径进行URL编码,否则API无法正确识别页面:
$encodedPage = [Uri]::EscapeDataString($page) $uri = "https://dev.azure.com/$organization/$project/_apis/wiki/wikis/MyWiki.wiki/pages?path=$encodedPage&api-version=7.0"
内容的提问来源于stack exchange,提问作者french_dev

