0

Hello I am trying to modify a JSON file by using PowerShell. I want to pass a variable from PowerhShell that will replace two values(Placeholder1 and Placeholder2)in the JSON file. I have the following for the first value which is not working.

PowerShell

$a = Get-Content $pathToJson -raw | ConvertFrom-Json
$a.update | % {if($_.name -eq 'placeholder1'){$_.name=$record_name}}
$a | ConvertTo-Json -Depth 20 | set-content $pathToJson

JSON

{
  "Comment": "Update record for Route 53",
  "Changes": [
    {
      "Action": "UPSERT",
      "ResourceRecordSet": {
        "Name": "placeholder1",
        "Type": "CNAME",
        "TTL": 300,
        "ResourceRecords": [
          {
            "Value": "placeholder2"
          }
        ]
      }
    }
  ]
}
1
  • 2
    There is no update property in your sample file. Which means your loop is not doing anything Commented Mar 16, 2018 at 18:29

1 Answer 1

0

Instead of converting to-and-from JSON, you can try just replacing the text, like this:

(Get-Content $pathToJson).Replace("placeholder1", $record_name) | Set-Content $pathToJson

You can chain the .Replace() function with another to update placeholder2 with whatever value it should be then.

Sign up to request clarification or add additional context in comments.

2 Comments

As a general rule directly manipulating strings in structured data is the wrong way to go.
Thanks @Valuator that worked like a charm, I chained the other placeholder in there as well as you suggested.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.