Powershell Json replacing — with â - json

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

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 Convertto-json output

Im getting a stream from shopify with powershell and converting it json readable text.
It was working fine for a couple of weeks but now is not returning the same data format.
$uri = "https://yourshop.myshopify.com/admin/api/2021-10/orders.json?limit=250"
$apikey = ""
$password = ""
$headers = #{"Authorization" = "Basic "+[System.Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($apikey+":"+$password))}
$products = Invoke-RestMethod -Uri $uri -FollowRelLink -contentType "application/json" -Method Get -Header $headers -Body $Body -MaximumFollowRelLink 5
$products | ConvertTo-Json -Depth 5 | Out-File C:\json\ordersdepth5.json -encoding utf8
it used to return neat json
{
"orders": [
{
"id": 4059713634402,
"admin_graphql_api_id": "gid://shopify/Order/4059713634402",
"app_id": 580111,
"browser_ip": "120.154.83.138",
"buyer_accepts_marketing": true,
"cancel_reason": null,
"cancelled_at": null,
but now it returns
["{\"orders\":[{\"id\":4122462257250,\"admin_graphql_api_id\":\"gid:\\/\\/shopify\\/Order\\/4122462257250\",\"
A bunch of slashes and rubbish
Is there an issue with the data stream? what should I look at.
Shopify wouldn't change formatting unless there is an api change?
I fixed the issue by moving the data into powershell to convert from and then convert to json.
$products | ConvertFrom-Json -AsHashtable | ConvertTo-Json -Depth 5 -Compress |Out-File C:\json\ordersdepth2.json -encoding utf8

Powershell ConvertFrom-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?

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!

Passing parameter values to a PowerShell script

The following is a snippet from my PowerShell script where the values for the parameters $book and $author are not getting substituted. Please suggest some techniques that I can apply to fix it or share some code that can help me out.
$body = #{
version = '1.0'
inactive = 'false'
yml = { "Service1:\n book: $book\n author: $author\n "} | ConvertFrom-Json
} | ConvertTo-Json
$request = Invoke-WebRequest -UseBasicParsing -Method Post -Uri $uri -Body
$body -Headers $headers -ContentType $contentType
$response = ConvertFrom-Json -InputObject $request.Content
You have some weird stuff going on in this line
... yml = { "Service1:\n book: $book\n author: $author\n "} | ConvertFrom-Json } | ConvertTo-Json
Because it says "do a script block with this body, and try to convert the script block to JSON".
So, if you want to have a JSON string in yml field, you have two options.
Write the proper JSON string yourself:
#{...put the rest of your elements here...; yml = "{Service1:'', book:'$book', author: '$author'}"
Populate a hashtable first and then convert it to JSON string:
#{...put the rest of your elements here...; yml = #{Service1=''; book='$book'; author='$author'} } | ConvertTo-Json