You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell中Invoke-RestMethod传变量报无效URI问题求助

解决Invoke-RestMethod URI解析错误问题

问题根源

你拼接的$response_text变量里额外添加了单引号,导致实际传入的URI是带单引号的字符串(比如'www.sample.net/...'),PowerShell会把单引号当成URI的一部分,自然无法正确解析主机名。

正确写法示例

方法1:去掉多余单引号直接拼接

$lastmonth11th = (Get-Date -Day 11).AddMonths(-1).ToString("yyyy-MM-dd")
$thismonth10th = (Get-Date -Day 10).ToString("yyyy-MM-dd")
# 移除字符串两端的单引号,直接拼接变量
$uri = "www.sample.net/data?key=1234&Accept=application/JSON&startdate=$lastmonth11th&endadte=$thismonth10th"
# 调用Invoke-RestMethod
$response = Invoke-RestMethod -Uri $uri -Method GET -Headers $Headers
$response | ConvertTo-Json -Depth 100 | Out-File "C:\Users\Admin\Desktop\sample.json" -Encoding UTF8

方法2:用PowerShell字符串插值(更简洁)

双引号包裹的字符串可以直接引用变量,无需手动用加号拼接:

$lastmonth11th = (Get-Date -Day 11).AddMonths(-1).ToString("yyyy-MM-dd")
$thismonth10th = (Get-Date -Day 10).ToString("yyyy-MM-dd")
# 双引号内自动替换变量值
$uri = "www.sample.net/data?key=1234&Accept=application/JSON&startdate=$lastmonth11th&endadte=$thismonth10th"
$response = Invoke-RestMethod -Uri $uri -Method GET -Headers $Headers
$response | ConvertTo-Json -Depth 100 | Out-File "C:\Users\Admin\Desktop\sample.json" -Encoding UTF8

额外建议

尽量给URI加上http://或https://前缀,避免PowerShell因默认协议解析规则出现异常,比如修改为:

$uri = "https://www.sample.net/data?key=1234&Accept=application/JSON&startdate=$lastmonth11th&endadte=$thismonth10th"

内容的提问来源于stack exchange,提问作者Lonestar fun

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 03:33:15