尝试从JSON转换Web请求,但总是收到以下错误:
Method invocation failed because [Microsoft.PowerShell.Commands.BasicHtmlWebResponseObject] does not contain a method named 'op_Addition'.
At C:UsersgmicskeiDesktoplastlogin_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
返回的对象类型为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)