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
相关产品推荐
相关产品推荐

