Powershell ConvertFrom-Json - json

i want to query the Neo4j Database with this Script.
https://github.com/teal-technology-consulting/Invoke-Neo4jQuery/blob/master/Invoke-Neo4jQuery.ps1
But always if i execute this i get this Error:
ConvertFrom-Json : Cannot convert 'System.Byte[]' to the type 'System.String' required by parameter 'InputObject'.
Specified method is not supported.
The Problem part is this:
$Result = Invoke-WebRequest -Uri $Uri2 -Method POST -Body $Query2 -credential $neo4jCreds2 -ContentType "application/json"
if ($Result) {
if (Test-Path -Path $FilePath -PathType Leaf) { Remove-Item -Path $FilePath }
$PsResult = ConvertFrom-Json -InputObject $Result.Content
How can i solve this Problem?

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"

How to extract json data from the Url using powershell script

I want my data from the url and want to filer it accordingly and export that data into the csv file
This is my code
Here $url variable contains the url
$defs = (Invoke-RestMethod -Uri ($url) -Method Get -UseDefaultCredentials)
$json = convertto-Json $defs
$json | Out-File D:\My_scripts\Final.json
$a = Get-Content D:\My_scripts\Final.json -raw | Out-String | ConvertFrom-Json
$arrOutput = #()
foreach($l2 in $a)
{
foreach($l3 in $l2.value)
{
#Write-Host $l3.id
$arr = #{}
$arr.id = $l3.id
$arr.name = $l3.name
$outarray = New-Object Psobject -Property $arr
$arrOutput += $outarray
}
}
$arrOutput | Export-Csv -Path D:\My_scripts\Final.csv -Delimiter "," -NoTypeInformation
But not able to get the values

Powershell Json replacing — with â

I have a script that gets data from a public API. I try to parse a value from the Json response into a variable. However it seems that when I Write-Host the variable it has replaced — with â.
Code:
$SetData = Invoke-RestMethod -Uri "https://mtgjson.com/api/v5/2XM.json" -ContentType "application/json" -Method GET
$Card = $SetData.data.cards | Where-Object { $_.name -eq "Adaptive Automaton" -and $_.isPromo -ne "true"}
Write-Host $Card.type -ForegroundColor Cyan
Output:
Artifact Creature — Construct
It looks like the strings returned by the Invoke-RestMethod here are encoded in 'ISO-8859-1' and not as you would expect in UTF-8.
This means you need to convert to UTF-8 where needed, something like this:
$encoding = [System.Text.Encoding]::GetEncoding('ISO-8859-1')
$SetData = Invoke-RestMethod -Uri "https://mtgjson.com/api/v5/2XM.json" -ContentType "application/json" -Method GET
$Card = $SetData.data.cards | Where-Object { $_.name -eq "Adaptive Automaton" -and !$_.isPromo}
# convert the string in '$Card.type' from encoding 'ISO-8859-1' into 'UTF-8'
$cardType = ([System.Text.Encoding]::UTF8).GetString($encoding.GetBytes($Card.type))
Write-Host $cardType -ForegroundColor Cyan
Output
Artifact Creature — Construct
To convert the whole json to UTF-8, You could use Invoke-WebRequest rather than Invoke-RestMethod:
$encoding = [System.Text.Encoding]::GetEncoding('ISO-8859-1')
$SetData = Invoke-WebRequest -Uri "https://mtgjson.com/api/v5/2XM.json" -Method Get
# convert $SetData.Content to UTF-8 and convert that from JSON
$content = ([System.Text.Encoding]::UTF8).GetString($encoding.GetBytes($SetData.Content)) | ConvertFrom-Json
$Card = $content.data.cards | Where-Object { $_.name -eq "Adaptive Automaton" -and !$_.isPromo}
Write-Host $Card.type -ForegroundColor Cyan

Powershell Script to create user and add to servicedesk suddenly not working

last year I created a PS script, that took care of automatically creating users and adding them to our servicedesk, we use a special user creation account for this, the credentials are locally saved in a text file. It all worked fine, however the script doesn't seem to work anymore, did the JIRA API change?
I get following error message: Invoke-Rest-Method: The remote server returned an error (401) Unauthorized at response = Invoke-Rest-Method -Uri...etc
I checked and our user creation account still has all the permissions to create users, I can manually create them and the log shows that the user also logs in normally through the script.
Hopefully somebody can help with my problem!
Here's the code:
$jiraCredentials = Get-Content -Raw -Path "C:\PowerShellScripts\New-AdUser\credentials.json" |ConvertFrom-Json
$bytes = [System.Text.Encoding]::ASCII.GetBytes("${$jiraCredentials.username}:${$jiraCredentials.password}")
$base64 = [System.Convert]::ToBase64String($bytes)
$basicAuthValue = "Basic $base64"
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.add("Authorization", $basicAuthValue)
$headers.add("X-Experimentalapi", "opt-in")
$headers.add("Content-Type", "application/json")
#$headers.add("X-Atlassian-Token", "nocheck")
$JSON = #"
{
"fullName": "$emailAddressClean",
"email": "$emailAddressClean"
}
"#
$response = Invoke-RestMethod -Uri https://jira.dilax.com/rest/servicedeskapi/customer -Method POST -Body $JSON -ContentType "application/json" -Headers $headers
#add customer to servicedesk
$JSON2 = #"
{
"usernames":[
"$emailAddressClean"
]
}
"#
$response2 = Invoke-RestMethod -Uri https://jira.dilax.com/rest/servicedeskapi/servicedesk/9/customer -Method POST -Body $JSON2 -ContentType "application/json" -Headers $headers
managed to fix it because the log in credentials didn't get transmitted correctly:
$jiraCredentials = Get-Content -Raw -Path "C:\PowerShellScripts\New-AdUser\credentials.json" |ConvertFrom-Json
$user = $jiraCredentials.username
$pass = $jiraCredentials.password
$pair = "${user}:${pass}"
$bytes = [System.Text.Encoding]::ASCII.GetBytes($pair)
$base64 = [System.Convert]::ToBase64String($bytes)
$basicAuthValue = "Basic $base64"

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!