1

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"
    } 
}
mklement0
  • 382,024
  • 64
  • 607
  • 775
Illya
  • 11
  • 1
  • 1
    When `$tmp = 'test.value1'`, `$_.$tmp` will make PowerShell attempt to resolve a property literally named `test.value1`, not one called `test` and then one called `value1` – Mathias R. Jessen Sep 22 '22 at 12:55
  • In short: There is no _built-in_ syntax for nested property access based on a _string value_ containing a property _path_ (e.g. `$prop = 'bar.baz'; $object.$prop` looks for a _single_ property literally named `bar.baz`), but there are workarounds; see the linked duplicate for details. – mklement0 Sep 22 '22 at 13:50

0 Answers0