PowerShell调用Invoke-RestMethod报401未授权错误求助
解决PowerShell调用Web API时的401未授权错误
以下是针对问题的具体解决步骤:
- 传递凭据到API请求
你已经通过Get-Credential获取了凭据变量$Cred,但未在Invoke-RestMethod中传递该凭据。需要添加-Credential参数将凭据传入请求:
Invoke-RestMethod -Method Post -Uri $url -Body $body -Credential $Cred
- 修正请求体格式
你的哈希表语法存在错误(使用了冒号:而非等号=,多余逗号),且多数Web API要求JSON格式的请求体。修正并转换为JSON:
$Body = @{ Timestamp = "2024-06-14T10:00:00Z" Value = "888" } | ConvertTo-Json
调用时需指定内容类型:
Invoke-RestMethod -Method Post -Uri $url -Body $body -Credential $Cred -ContentType 'application/json'
- 匹配API的认证方式
如果API使用Bearer Token认证,需添加授权请求头:
$token = "你的访问令牌" $headers = @{ Authorization = "Bearer $token" } Invoke-RestMethod -Method Post -Uri $url -Body $body -Headers $headers -ContentType 'application/json'
若为NTLM/Kerberos认证,可添加对应认证参数:
Invoke-RestMethod -Method Post -Uri $url -Body $body -Credential $Cred -Authentication Ntlm -ContentType 'application/json'
- 验证凭据有效性
确认Get-Credential输入的用户名/密码对目标API拥有写入权限,部分场景需使用域名\用户名格式(如domain\user)。
内容的提问来源于stack exchange,提问作者Manoj kumar
相关产品推荐
相关产品推荐

