I have one json file mytest.json
like below I want to update values using PowerShell script
update.json
{ "update": [ { "Name": "test1", "Version": "2.1" }, { "Name": "test2", "Version": "2.1" } ] }
I want to write a PowerShell script where if Name=="test1" I want to update Version= "3"
How can i do it using parameters?
Use the Invoke-Request Command in PowerShell We will use this example to get some JSON to work with. Open up the PowerShell console. Run the Invoke-WebRequest command to query the GitHub API, as shown below. The code snippet below assigns all of the output the cmdlet returns to the $webData variable for processing.
The Get-Content command is a PowerShell command that reads an item's content. This command takes a Path parameter that specifies the item's location; the content is usually text data. The JSON-formatted string is also text data; this command can read a JSON file and output it as a string to the shell.
Here is a way :
$a = Get-Content 'D:\temp\mytest.json' -raw | ConvertFrom-Json $a.update | % {if($_.name -eq 'test1'){$_.version=3.0}} $a | ConvertTo-Json -depth 32| set-content 'D:\temp\mytestBis.json'
According to @FLGMwt and @mikemaccana I improve the ConvertTo-Json
with -depth 32
because the default depth value is 2 and for object deeper than 2 you will receive class informations in spite of objects.
I have also faced the same kind of issue. I was looking to change the records of the below JSON file
{ "SQS_QUEUE_URL": "https://que-url.com/server1", "SQS_EVENTS_QUEUE_URL": "https://events-server.com/server1/development_events", "REGION": "region1", "BUCKET": "test-bucket", "AE_WORK_PATH": "C:\\workpath\\path1", "ENV": "env" }
Finally, I managed to find the easiest way to generate a JSON file from Powershell.
$json = Get-Content "c:\users\bharat.gadade\desktop\test.json" | ConvertFrom-Json $json.SQS_QUEUE_URL = "https://que-url.com/server2" $json.SQS_EVENTS_QUEUE_URL = "https://events-server.com/Server2/development_events" $json.REGION = "region1 " $json.BUCKET = "test-bucket" $json.AE_WORK_PATH = "C:\workpath\path1" $json.ENV = "env" $json | ConvertTo-Json | Out-File "c:\users\bharat.gadade\desktop\test.json"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With