Replacing multiple values in JSON file using Powershell

Viewed 20

I need to dynamically change json content by subtracting only variables that start with "_" My json:

{
    "test":  {
               "value1":  "test1",
               "value12":  "test2"
             },
    "test2": {
               "value3":  "test1",
               "value4":  "test2"
             }
}

But my script does not work:

$variables = @(
    [pscustomobject]@{Name='_test__value1'; Value='123'}
    [pscustomobject]@{Name='test2__value3'; Value='123'}
    [pscustomobject]@{Name='test__value1'; Value='123'}
    [pscustomobject]@{Name='_test2__value3'; Value='123'}
)

foreach($variable in $variables)
{
    if ($variable.Name -like '_*')
    {
        $tmp = $variable.Name -replace '__','.' -replace '_','' 
        $tmpV = $variable.Value

        Get-Content "C:\temp\config.json" -raw | ConvertFrom-Json |ForEach-Object { $_.$tmp = $tmpV; $_} | ConvertTo-Json -depth 32| set-content "C:\temp\config.json"
    } 
}
0 Answers
Related