Try to convert a web request from JSON but always get the below error:
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
Here is my code:
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
Can you please advise?
Thanks, Gabor
The objects returned by
Invoke-WebRequest -UseBasicParsing
are of typeMicrosoft.PowerShell.Commands.BasicHtmlWebResponseObject
:This type has no
.Value
property.Using it as-is, which your code therefore does, is the source of the problem:
$QueryResults += $Results
stores the$Results
variable as-is.+=
tries to "add" to an instance, but no such operation is defined for this type.As an aside: In order to collect the
$Results
values in an array,$QueryResults
would have to be initialized as an array before entering the loop, but note that building an array iteratively with+=
should be avoided, due to its inefficency - see this answer.You can solve all problems by using
Invoke-RestMethod
instead, which automatically parses JSON responses into objects ([pscustomobject]
instances):