1

尝试从 JSON 转换 Web 请求,但总是得到以下错误:

Method invocation failed because [Microsoft.PowerShell.Commands.BasicHtmlWebResponseObject] does not contain a method named 'op_Addition'.
At C:\Users\gmicskei\Desktop\lastlogin_users_azureAD.ps1:39 char:17
+                 $QueryResults += $Results
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (op_Addition:String) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

这是我的代码:

do {
            $Results = Invoke-WebRequest -Headers $authHeader1 -Uri $Uri -UseBasicParsing -Method "get" -ContentType "application/json"

        if ($Results.value) {
            $QueryResults += $Results.value
        } else {
            $QueryResults += $Results
        }

        $uri = $Results.'@odata.nextlink'
    } until (!($uri)) 

    $QueryResultsjson = $QueryResults | ConvertFrom-Json

你能给些建议么?

谢谢, 加博尔

4

1 回答 1

2

返回的对象Invoke-WebRequest -UseBasicParsing类型为Microsoft.PowerShell.Commands.BasicHtmlWebResponseObject

  • 这种类型没有.Value属性。

  • 因此,您的代码按原样使用它是问题的根源:

    • 在第一次循环迭代中,$QueryResults += $Results按原样存储$Results变量。
    • 随后的循环迭代中,+=尝试“添加”到一个实例,但没有为这种类型定义这样的操作。

顺便说一句:为了收集数组中的$Results,必须在进入循环之前将其初始化为数组,但请注意,由于效率低下,应避免使用迭代构建数组- 请参阅此答案$QueryResults+=


您可以通过使用来解决所有问题Invoke-RestMethod,它会自动将 JSON 响应解析为对象[pscustomobject]实例):

$results = do {

  # Calls the web service and automatically parse its JSON output
  # into an object ([pscustomobject] instance).
  $result = Invoke-RestMethod -Headers $authHeader1 -Uri $Uri -Method "get" -ContentType "application/json"

  # Output the result at hand, to be collected across all
  # iterations in the $results variable being assigned to.
  # (.value is assumed to be a top-level property in the JSON data received).
  $result.value 
 
  # Determine the next URI, if any.
  # Since $result is now an *object*, property access should work.
  $uri = $result.'@odata.nextlink'

} while ($uri)

于 2020-12-01T23:34:01.243 回答