Azure DevOps中PowerShell调用Invoke-RestMethod报错求助
问题:PowerShell调用RestAPI时出现APIKey参数错误
在Azure DevOps中使用PowerShell脚本调用RestAPI,脚本代码如下:
$Body = @{ "OperationType" = "new" "ChangeType" = "ZMCR" "LongDescription" = "Test Description of Change" "ShortDescription" = "Test Short Description" "CycleTypeId" = "8200000083" "FuncUser" = "123" "ProductId" = "123" "ExtrefNumber" = "Ext Ref Number" "ChangeTypeCd" = "ZMHF" "StepApproverPartnerid" = "5048" } | ConvertTo-Json # Send a POST request including bearer authentication. $params = @{ 'Method' = 'Post' 'Uri' = 'https://abcdefgh' 'APIKey' = '6789034' 'Accept' = '*/*' 'Body' = '$Body' 'ContentType' = 'application/json' } Invoke-RestMethod @params
执行管道时出现如下错误:
2022-10-14T16:11:19.6120102Z Invoke-RestMethod : A parameter cannot be found that matches parameter name 'APIKey'. 2022-10-14T16:11:19.6122357Z At D:\a\_temp\15010f41-4006-46a8-8ae1-a7552a46383a.ps1:30 char:20 2022-10-14T16:11:19.6125176Z + Invoke-RestMethod @params 2022-10-14T16:11:19.6125924Z + ~~~~~~~ 2022-10-14T16:11:19.6126849Z + CategoryInfo : InvalidArgument: (:) [Invoke-RestMethod], ParentContainsErrorRecordException 2022-10-14T16:11:19.6128067Z + FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
解决方法
错误核心是PowerShell的Invoke-RestMethod命令没有APIKey这个参数,同时脚本里的Body参数写法也存在问题,以下是修正步骤:
1. 用请求头传递API密钥
API密钥需要通过请求头(Headers)传递,具体字段名需参考目标API的文档,常见格式有两种:
- 格式一:使用
X-API-Key作为头字段 - 格式二:使用
Authorization头,值为ApiKey <你的密钥>或Bearer <你的密钥>
2. 修正Body参数写法
原脚本中'Body' = '$Body'会把字符串$Body作为请求体发送,而非变量$Body的实际值,需去掉单引号,直接使用变量名。
修正后的脚本示例
以X-API-Key格式为例:
$Body = @{ "OperationType" = "new" "ChangeType" = "ZMCR" "LongDescription" = "Test Description of Change" "ShortDescription" = "Test Short Description" "CycleTypeId" = "8200000083" "FuncUser" = "123" "ProductId" = "123" "ExtrefNumber" = "Ext Ref Number" "ChangeTypeCd" = "ZMHF" "StepApproverPartnerid" = "5048" } | ConvertTo-Json # 构建请求头,根据API要求调整字段名 $requestHeaders = @{ "X-API-Key" = "6789034" } $params = @{ 'Method' = 'Post' 'Uri' = 'https://abcdefgh' 'Headers' = $requestHeaders 'Accept' = '*/*' 'Body' = $Body 'ContentType' = 'application/json' } Invoke-RestMethod @params
如果API要求用Authorization头,只需修改requestHeaders部分:
$requestHeaders = @{ "Authorization" = "ApiKey 6789034" }
内容的提问来源于stack exchange,提问作者gaurav sharma
相关产品推荐
相关产品推荐

