ConverFrom-JSON: Invalid JSON Primitive DOT - json

So what I'm trying is to get the id which is in the JSON under value. I'm running:
Invoke-RestMethod -Uri $uri -Headers $authToken -Method Get
And getting:
#odata.context value
-------------- -----
https://graph.microsoft.com/beta/$metadata {#{id=09eef6d9-6e66-4676-8d0f-c66e3174d5ea; ...}}
#deviceManagement/depOnboardingSettings
The output I'm trying to achive simply is $enrollId = 09eef6d9-6e66-4676-8d0f-c66e3174d5ea.
I tried to use | Out-String and | ConvertFrom-Json but the error message persists:
ConvertFrom-Json : Invalid JSON-Primitiv: .

Got it.. It was a http response.
$uri = "https://graph.microsoft.com/beta/deviceManagement/depOnboardingSettings"
$enrollTokenId = Invoke-RestMethod -Uri $uri -Headers $authToken -Method Get
$enrollTokenId = ($enrollTokenId.value).id
PS C:\PS-azure\imports> $enrollTokenId
09eef6d9-6e66-4676-8d0f-c66e3174d5ea

Related

MSGraph - Invoke-WebRequest (403) Forbidden

I have a delegate App with Directory.ReadWrite.All permissions and a PS script to auth users over the app. It works when I use GET but I'm getting Forbidden when try PATCH method
Here's the part of that script:
$uri = "https://graph.microsoft.com/v1.0/devices/1111-2222-3333-4444-5555"
$method = "PATCH"
$body = '{
"extensionAttributes": {
"extensionAttribute2": "text"
}
}'
Invoke-WebRequest -Method $method -Uri $uri -Body $body -ContentType "application/json" -Headers #{Authorization = "Bearer $token"} -UseBasicParsing -ErrorAction Stop
Another thing: when using device ObjectID to construct Uri I'm getting the 403 Forbidden but if I use a $filter over a DeviceID I get 405 Method not allowed. Does it mean it doesn't like a filter and have to stick with the ObjectID? Is there a way when I run the GET with $filter to save in a variable only ObjectID within JSON query?
Thanks
sorted it, I needed Directory.AccessAsUser.All and used this to get the objectId variable:
$DsregCmdStatus = dsregcmd /status
if($DsregCmdStatus -match "DeviceId")
{
$DeviceId = $DsregCmdStatus -match "DeviceID"
$DeviceId = ($DeviceId.Split(":").trim())
$DeviceId = $DeviceId[1]
}
# Find Id
$uri = "https://graph.microsoft.com/v1.0/devices?`$filter=deviceId eq '$DeviceId'"
$method = "GET"
# Run Graph API query
$query = Invoke-WebRequest -Method $method -Uri $uri -ContentType "application/json" -Headers #{Authorization = "Bearer $token"} -UseBasicParsing -ErrorAction Stop
$output = ConvertFrom-Json $query.Content
$id = $output.value
$id = $id.id
Write-Host "Machine ID is $id"

Powershell: Unable to parse json returned from Invoke-RestMethod

I try to parse a json string returned from an API call.
$Response = Invoke-RestMethod -Uri $URIValue -Method Post -Headers $Headers -Body $requestBody -ContentType 'application/json; charset=utf-8'
$Response #Returns: {"results":[{"tables":[{"rows":[{"[Quantity]":200}]}]}]}
Now that I try to parse it Response | ConvertFrom-Json I get the following error: ConvertFrom-Json: Conversion from JSON failed with error: Unexpected character encountered while parsing value: . Path '', line 0, position 0.
What am I doing wrong?
The actual solution:
$Response.Substring(1) | ConvertFrom-Json

SurveyMonkey creating a collector in Powershell returning "The body provided was not a proper JSON string

I'm using Powershell to automate a survey creation, adding a collector, and sending the survey invitation - a pretty common use case. I was able to create a survey but I'm running into an issue in creating the collector. I created a collector via Postman but I get the error "1001 - The body provided was not a property JSON string" when using Powershell. I've tried everything I can think of but continue to get the error no matter how I create the JSON. Here is the code I'm using:
$SurveyCollector = [PSCustomObject]#{ type = 'email' }
$BodyText = $SurveyCollector | Select-Object -Property type |ConvertTo-Json -Depth 100 -Compress
$Results = Invoke-RestMethod -Uri $uri -StatusCodeVariable "ExtIDscv" -SkipHttpErrorChe -Method
Post -ContentType "application/json" -Authentication Bearer -Token $SecureToken -body -$BodyText
I'm sure I'm missing something simple. I'd appreciate any help.
The answer was more simple than what tripleee suggested. I had introduced a -$BodyText into the call and didn't catch it. I removed it and it works just fine.
$Results = Invoke-RestMethod -Uri $uri -StatusCodeVariable "ExtIDscv" -SkipHttpErrorChe -Method
Post -ContentType "application/json" -Authentication Bearer -Token $SecureToken -body -$BodyText

PowerShell JSON Headers not Converting correctly

I am using an API REST call, but the problem is that it for some reason is not passing the header value correctly. I am getting an error about it not converting from "System.String" to "System.Collections.IDictionary".
The code is:
$Headers = New-Object 'System.Collections.Generic.Dictionary[[String],[String]]'
$Headers.Add('X-CENTRIFY-NATIVE-CLIENT', 'true')
$Headers.Add('Content-Type', 'application/json')
$Body = #{
TenantId = 'ID'
User = 'cloudadmin#andrew1.com'
Version = '1.0'
}
#$wr = Invoke-WebRequest -Method Post -Uri $url -Headers $Headers -Body $Body -Verbose
Invoke-RestMethod -Uri "https://uri/Security/StartAuthentication" -Method Post -Headers ($Headers | ConvertTo-Json -Compress) -UseBasicParsing -Body $Body
But when I execute I get this error (FQID):
Invoke-RestMethod : Cannot bind parameter 'Headers'. Cannot convert the "{
"X-CENTRIFY-NATIVE-CLIENT": "true",
"Content-Type": "application/json"
}" value of type "System.String" to type "System.Collections.IDictionary".
At line:31 char:109
+ ... tication" -Method Post -Headers ($Headers1 | ConvertTo-Json) -UseBas ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Invoke-RestMethod], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
I have tried my headers being like this as well:
$headers = #{
'Content-Type'= 'application/json'
'X-CENTRIFY-NATIVE-CLIENT'= 'true'
}
But I still get that same error. It is odd that it keeps complaining about this reference; This library is not native to PoSH. Is there a DLL I should load or is there a better way to go about this?
The -Headers parameter expects a dictionary, not a json object.
Pass $Headers directly:
$uri = "https://uri/Security/StartAuthentication"
Invoke-RestMethod -Uri $uri -Method Post -Headers $Headers -UseBasicParsing -Body $Body
You can inspect parameter details with Get-Help:
PS > Get-Help Invoke-WebRequest -Parameter Headers
-Headers <IDictionary>
Required? false
Position? Named
Accept pipeline input? false
Parameter set name (All)
Aliases None
Dynamic? false
I took the json conversion out of the header on your invoke restmethod. That part will need to be done on your payload $Body. Give this a try.
$Headers = #{}
$Headers.Add('X-CENTRIFY-NATIVE-CLIENT', 'true')
$Headers.Add('Content-Type', 'application/json')
$Body = #{
TenantId = 'ID'
User = 'cloudadmin#andrew1.com'
Version = '1.0'
}
$Body = ($Body | ConvertTo-Json)
#$wr = Invoke-WebRequest -Method Post -Uri $url -Headers $Headers -Body $Body -Verbose
Invoke-RestMethod -Uri "https://uri/Security/StartAuthentication" -Method Post -Headers $Headers -UseBasicParsing -Body $Body

Manipulate json and send it into web request using Powershell

I'm trying to manipulate a json object and send it as content into the body of a put / post web request. The source of my json is a file on my disk.
This is my Powershell script:
$urlBase = 'https://mysite.myapp.com/service/api/Item/'
$myJson = (Get-Content 'file.json' | ConvertFrom-JSON)
# Then I manipulate my object
$id = $myJson.id
$myJson.version = '1.2.3.4'
# Request
$response = Invoke-RestMethod -Uri ($urlBase + $id) -Method Put -Body $myJson -ContentType 'application/json' -Headers $hdrs
When I execute my script y get this error message:
Invoke-RestMethod : The remote server returned an error: (400) Bad Request.
At line:18 char:17
+ ... $response = Invoke-RestMethod -Uri ($urlBase + $id) -Method Put -Body ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
If I change my $myJson asignment for this the request works fine...
$myJson = Get-Content 'file.json'
... , but then I can't manipulate my json before send it.
Edited:
If I try to convert back using ConvertTo-Json I get the same error:
$convertedBack = $myJson | ConvertTo-Json
# Request
$response = Invoke-RestMethod -Uri ($urlBase + $id) -Method Put -Body $convertedBack -ContentType 'application/json' -Headers $hdrs
As pointed out in the comments: you need to convert your object back to JSON using the ConvertTo-Json cmdlet.
I see that you've tried that now and had the same problem. So I ask you this: is the value of $convertedBack exactly what you expected? Dump it to file and check!
The reason I am suspicious of this detail is that ConvertTo-Json has a little gotcha in it. Specifically the -Depth parameter which can cause some data loss.
-Depth
Specifies how many levels of contained objects are included in the JSON representation. The default value is 2.
Example Without -Depth
$basicJsonObject = #"
{
"name": "George",
"properties": {
"mood": "jovial",
"coffee": {
"hasCoffee": true,
"mugContents": {
"milk": false,
"doubleShot": true
}
}
}
}
"#
$psObject = ConvertFrom-Json -InputObject $basicJsonObject
Write-Host "Freshly Imported"
Write-Host "DoubleShot = $($psObject.properties.coffee.mugContents.doubleShot)"
$convertedBack = ConvertTo-Json -InputObject $psObject
$reConverted = ConvertFrom-Json -InputObject $convertedBack
Write-Host "Re-Converted"
Write-Host "DoubleShot = $($reConverted.properties.coffee.mugContents.doubleShot)"
Results
Freshly Imported
DoubleShot = True
Re-Converted
DoubleShot =
Example With -Depth
Change one line of code:
$convertedBack = ConvertTo-Json -InputObject $psObject -Depth 5
Results
Freshly Imported
DoubleShot = True
Re-Converted
DoubleShot = True
Note how the new results include the value from the $reConverted variable. This is because the data is not lost further upstream!