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"
          }
        ]
      }
    }
  ]
}
Eli
  • 1
  • 1
  • 1
  • 2
    There is no update property in your sample file. Which means your loop is not doing anything – Matt Mar 16 '18 at 18:29

1 Answers1

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.

Valuator
  • 3,262
  • 2
  • 29
  • 53
  • 1
    As a general rule directly manipulating strings in structured data is the wrong way to go. – EBGreen Mar 16 '18 at 18:36
  • 1
    Thanks @Valuator that worked like a charm, I chained the other placeholder in there as well as you suggested. – Eli Mar 16 '18 at 19:55