I have the using the REST API to get the result, then I get the Json file, ApiConnectionjson:
$token = $(Token)
$header = @{authorization = "Bearer $token"}
$url = "https://management.azure.com/xxxx?api-version=2018-07-01-preview"
$result = Invoke-RestMethod -Uri $url -Method Get -ContentType "application/json" -Headers $header
$ApiConnectionjson = $result | ConvertTo-Json -depth 100
Write-Host "$ApiConnectionjson"
Now, I get the Json file via above powershell. No need to pay attention to the above code, it is not the key point.
The ApiConnectionjson
like:
{
"kind": "V2",
"properties": {
"displayName": "xxxx",
"authenticatedUser": {
"name": "xxx"
},
"overallStatus": "Connected",
"statuses": [
{
"status": "Connected"
}
],
"connectionState": "Enabled",
...
...
}
Now I want add key value "apiVersion": "2016-06-01",
in the first line to the json, like:
{
"apiVersion": "2016-06-01",
"kind": "V2",
"properties": {
"displayName": "xxxx",
"authenticatedUser": {
"name": "xxx"
},
"overallStatus": "Connected",
"statuses": [
{
"status": "Connected"
}
],
"connectionState": "Enabled",
...
...
}
I have tried the method in this thread: but my powershell does not support the method pscustomobject
.
Edit:
My test code:
$ApiConnectionjson = $ApiConnectionjson | ConvertFrom-Json
$ApiConnectionjson += [pscustomobject] @{ apiVersion = '2016-06-01' }
$ApiConnectionjson | ConvertTo-Json -Depth 10
Error message:
Method invocation failed because [System.Management.Automation.PSObject] does not contain a method named ‘op_Addition’.
At D:a_tempazureclitaskscript1679387440203_inlinescript.ps1:17 char:1
3
Answers
Please see the below code, this applies the new property using the
add-member
cmdlet prior to converting it to JSON as the object itself is easier to manipulate, then it uses theselect
cmdlet to force the position of the property to be the 1st value.Unfortunately,
Invoke-RestMethod
doesn’t have a-AsHashTable
parameter which would make things easier (see:#19378
Invoke-RestMethod
should have an-AsHashTable
switch). In other words, you will need to use theAdd-Member
cmdlet for this:In case you want
"apiVersion": "2016-06-01"
to be added in the first line, I would replace the concerned (top) object layer:Or use the Select-Object with a calculated property:
I try to explain the error as other answers are already given:
as long as it’s an collection the
+=
is unknown.