【问题标题】:Why does this PowerShell Invoke-RestMethod POST throw an exception?为什么这个 PowerShell Invoke-RestMethod POST 会引发异常?
【发布时间】:2018-01-13 03:39:24
【问题描述】:

我有以下引发异常的 PowerShell 脚本,如下所示。我怎样才能Invoke-RestMethod -Method Post 授权$bearerHeader

$content = New-Object System.Net.Http.StreamContent $snapshot;
$content.CopyToAsync($snapshot);
try {
    $encodedPath = [Text.Encoding]::ASCII.GetBytes($this.snapshotPath)
    $hmacsha = New-Object System.Security.Cryptography.HMACSHA512
    $hmacsha.key = [Convert]::FromBase64String($this.apikey);
    $bearerToken = $hmacsha.ComputeHash($encodedPath)

    $bearerToken = [Convert]::ToBase64String($bearerToken)
    $bearerToken = $bearerToken.Split('=')[0]
    $bearerToken = $bearerToken.Replace('*', '-')
    $bearerToken = $bearerToken.Replace('+', '_')

    $bearerHeader = @{ "Authorization" = ("Bearer", $bearerToken -join " ") }
    $url = ($this.baseAddress, $this.snapshotPath -join "");
    $resp = Invoke-RestMethod -Method Post -Uri $this.snapshotPath -ContentType "application/octet-stream" -Body $content -Headers $bearerToken
} catch [Exception] {
    Write-Host "Exception: "$_.Exception.Message -ForegroundColor Red;
}

无法将“System.String”类型的“uZZETvpJdAIqIH_235oFjan3wS_M582332jmiJjm23jJvJxJwHm0JtWSkhg5qj_7jGDI_s3IFx2ozx5wyQXCA”值转换为“System.Collections.IDictionary”类型。

【问题讨论】:

  • Invoke-RestMethod ... -Headers $bearerToken -> Invoke-RestMethod ... -Headers $bearerHeader
  • 抱歉,这是什么意思?我不明白。你能说得更详细一点吗?
  • 一个是你目前拥有的,另一个是你应该拥有的。很清楚。您目前在 -Headers 参数中传递 $bearerToken 但您应该传递 $bearerHeader。

标签: powershell exception


【解决方案1】:

根据 cmets,这是:

$resp = Invoke-RestMethod -Method Post -Uri $this.snapshotPath -ContentType "application/octet-stream" -Body $content -Headers $bearerToken

需要:

$resp = Invoke-RestMethod -Method Post -Uri $this.snapshotPath -ContentType "application/octet-stream" -Body $content -Headers $bearerHeader

-Headers 参数需要一个哈希表作为其输入,您的代码将其创建为 $bearerHeader 但您没有使用它。

【讨论】:

  • 看起来 $resp 没有返回任何东西。如何通过 Invoke-RestMethod -Method Post 获取返回值?我必须决定 if($rest -eq $flase) 等。
  • 我在你的另一个问题上回答了这个问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-01
  • 1970-01-01
相关资源
最近更新 更多