Do-until 循环出错(powershell)

Do-untill loop getting error (powershell)

尝试从 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

能请教一下吗?

谢谢, 嘉宝

Invoke-WebRequest -UseBasicParsing are of type Microsoft.PowerShell.Commands.BasicHtmlWebResponseObject返回的对象:

  • 此类型没有.Value 属性.

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

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

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


您可以使用 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)