powershell替换target.json中的值。

发布于 2025-01-23 06:11:00 字数 4803 浏览 0 评论 0 原文

我有一个大的目标JSON文件(parameters_general.json),其中设置了所有部署的常见设置。 对于每个层,我都有另一个JSON文件(ex:parameters_dev.json,parameters_test.json,....)设置在一个需要中设置为tobe。将其添加到General.json中,或者在总体上已经在总体上覆盖它。

例如:parameters_general.json

{ 
  "general": {
    "db_Policy": {
    "type": "Periodic",
    "databaseAccountOfferType": "Standard",
    "periodicModeProperties": {
      "backupIntervalInMinutes": 240,
      "backupRetentionIntervalInHours": 8,
      "backupStorageRedundancy": "Local"
    }      
  },
  "databases": [
    { 
      "name": "CtrlWps", 
      "Containers": [
        {
          "name": "ControllerAuthentication",
          "partitionKey": "id"
        }
      ],
      "ContainersTTL": []
    },
    { 
      "name": "CpoOcpi",
      "Containers": [
        {
          "name": "Cpos",
          "partitionKey": "cpoId"
        },          
        {
          "name": "OcpiCdrLastRecoveries",
          "partitionKey": "id"
        },
        {
          "name": "Routes",
          "partitionKey": "ocpiCpoId"
        }
      ],
      "ContainersTTL": [
        {
          "name": "OcpiCdrs",
          "partitionKey": "pk",
          "ttl": 172800
        },
        
        {
          "name": "OcppTransactionIds",
          "partitionKey": "pk",
          "ttl": 172800
        },
        {
          "name": "Sessions",
          "partitionKey": "pk",
          "ttl": 172800
        }     
      ]
    }
  ],
  "system_engineers": [
  ],
 }
}

如果我想更新。

例如:parameters_test.json

{ 
  "general": {
    "system_engineers": [
      {
        "name": "hans",
        "AppPrincipalId": "<id>",
        "permissions": [
          "get",
          "list"
        ]
      },
      {
        "name": "John do",
        "AppPrincipalId": "<pid>",
        "permissions": [
          "all"
        ]
      }
    ]
  }
}

此工作,将用户添加到parameters_general.json中的空“ sytem_engineers”节点。

但是,如果我只想更改较低节点上的设置示例:

ex:parameters_dev.json

{
  "general": {
    "databases": [
        { 
          "name": "CtrlWps", 
          "Containers": [
            {
              "name": "ControllerAuthentication",
              "partitionKey": "pk"
            }
          ]
        }
    ]
  }
}

用于在一个数据库中替换partitionKey的数据库中,它会替换整个“数据库”部分,因此我丢失了目标中所有其他数据库配置。

我使用的代码如下。

function ExtendJSON($base, $ext)
{
    $propNames = $($ext | Get-Member -MemberType *Property).Name
    foreach ($propName in $propNames) {
        if ($base.PSObject.Properties.Match($propName).Count) {
            if ($base.$propName.GetType().Name -eq "PSCustomObject")
            {
                $base.$propName = ExtendJSON $base.$propName $ext.$propName
            }
            else
            {
                $base.$propName = $ext.$propName
            }
        }
        else
        {
            $base | Add-Member -MemberType NoteProperty -Name $propName -Value $ext.$propName
        }
    }
    return $base
}

$tier = 'dev'  
$parametersJsonGeneral = Get-Content -Path "./parameters/parameters_general.json" | ConvertFrom-Json
#Write-Output "#####################"
$parametersJsonTier = Get-Content -Path "./parameters/parameters_$($tier).json" | ConvertFrom-Json   # overwrites existing values in $parametersJsonGeneral
ExtendJSON $parametersJsonGeneral $parametersJsonTier 

是否有一种方法可以从最低级别到更高的设置上循环并仅替换这些设置?

提出的答案确实仅能工作一个第一级,

function merger ($target, $source) {
    $source.psobject.Properties | ForEach-Object {
        if ($_.TypeNameOfValue -eq 'System.Management.Automation.PSCustomObject' -and $target."$($_.Name)" ) {
            merger $target."$($_.Name)" $_.Value
        }
        else {
            $target | Add-Member -MemberType $_.MemberType -Name $_.Name -Value $_.Value -Force
        }
    }
}


$Json1 ='{
    "a": {
      "b":"asda"
    },
    "c": "asdasd"
  }
  ' | ConvertFrom-Json
  
  $Json2 = '{
    "a": {
      "b":"d"
    }
  }
  ' | ConvertFrom-Json

merger $Json1 $Json2

中的i松开数据已经消失了!

$Json1 ='{
    "a": {
      "b": [
          { 
            "name": "admin",
            "appconfig": {
                "test1": true,
                "test2": false
            }
          }
        ]
    },
    "c": "asdasd"
  }
  ' | ConvertFrom-Json
  
  $Json2 = '{
    "a": {
        "b": [
            { 
              "name": "admin",
              "appconfig": {
                  "test1": false
              }
            }
          ]
    }
  }
  ' | ConvertFrom-Json

merger $Json1 $Json2

{
  "a": {
    "b": [
      {
        "name": "admin",
        "appconfig": {
          "test1": false
        }
      }
    ]
  },
  "c": "asdasd"
}

但是使用此i在$ JSON1 TEST2

I have a big target json file (parameters_general.json) where all common settings for a deployment are set.
For each tier I have another json file (ex: parameters_dev.json, parameters_test.json, ....) Settings set in one needs tobe added to the general.json, or overwrite it when already in general.

ex: parameters_general.json

{ 
  "general": {
    "db_Policy": {
    "type": "Periodic",
    "databaseAccountOfferType": "Standard",
    "periodicModeProperties": {
      "backupIntervalInMinutes": 240,
      "backupRetentionIntervalInHours": 8,
      "backupStorageRedundancy": "Local"
    }      
  },
  "databases": [
    { 
      "name": "CtrlWps", 
      "Containers": [
        {
          "name": "ControllerAuthentication",
          "partitionKey": "id"
        }
      ],
      "ContainersTTL": []
    },
    { 
      "name": "CpoOcpi",
      "Containers": [
        {
          "name": "Cpos",
          "partitionKey": "cpoId"
        },          
        {
          "name": "OcpiCdrLastRecoveries",
          "partitionKey": "id"
        },
        {
          "name": "Routes",
          "partitionKey": "ocpiCpoId"
        }
      ],
      "ContainersTTL": [
        {
          "name": "OcpiCdrs",
          "partitionKey": "pk",
          "ttl": 172800
        },
        
        {
          "name": "OcppTransactionIds",
          "partitionKey": "pk",
          "ttl": 172800
        },
        {
          "name": "Sessions",
          "partitionKey": "pk",
          "ttl": 172800
        }     
      ]
    }
  ],
  "system_engineers": [
  ],
 }
}

If I want to updatethis with.

ex: parameters_test.json

{ 
  "general": {
    "system_engineers": [
      {
        "name": "hans",
        "AppPrincipalId": "<id>",
        "permissions": [
          "get",
          "list"
        ]
      },
      {
        "name": "John do",
        "AppPrincipalId": "<pid>",
        "permissions": [
          "all"
        ]
      }
    ]
  }
}

This works, the users are added to the empty "sytem_engineers" node in the parameters_general.json.

However, If I just want to change a setting on a lower node example:

ex: parameters_dev.json

{
  "general": {
    "databases": [
        { 
          "name": "CtrlWps", 
          "Containers": [
            {
              "name": "ControllerAuthentication",
              "partitionKey": "pk"
            }
          ]
        }
    ]
  }
}

for replacing the partitionKey in one of the databases it replaces the whole "databases" part so I lose all other database configurations in the target.

The code I use is the following.

function ExtendJSON($base, $ext)
{
    $propNames = $($ext | Get-Member -MemberType *Property).Name
    foreach ($propName in $propNames) {
        if ($base.PSObject.Properties.Match($propName).Count) {
            if ($base.$propName.GetType().Name -eq "PSCustomObject")
            {
                $base.$propName = ExtendJSON $base.$propName $ext.$propName
            }
            else
            {
                $base.$propName = $ext.$propName
            }
        }
        else
        {
            $base | Add-Member -MemberType NoteProperty -Name $propName -Value $ext.$propName
        }
    }
    return $base
}

$tier = 'dev'  
$parametersJsonGeneral = Get-Content -Path "./parameters/parameters_general.json" | ConvertFrom-Json
#Write-Output "#####################"
$parametersJsonTier = Get-Content -Path "./parameters/parameters_$($tier).json" | ConvertFrom-Json   # overwrites existing values in $parametersJsonGeneral
ExtendJSON $parametersJsonGeneral $parametersJsonTier 

Is there a way to loop over the settings from the lowest level up to the higher, and replace only these?

The proposed answer does only work one 1st level THIS WORKS

function merger ($target, $source) {
    $source.psobject.Properties | ForEach-Object {
        if ($_.TypeNameOfValue -eq 'System.Management.Automation.PSCustomObject' -and $target."$($_.Name)" ) {
            merger $target."$($_.Name)" $_.Value
        }
        else {
            $target | Add-Member -MemberType $_.MemberType -Name $_.Name -Value $_.Value -Force
        }
    }
}


$Json1 ='{
    "a": {
      "b":"asda"
    },
    "c": "asdasd"
  }
  ' | ConvertFrom-Json
  
  $Json2 = '{
    "a": {
      "b":"d"
    }
  }
  ' | ConvertFrom-Json

merger $Json1 $Json2

However with this I loose data in $Json1

$Json1 ='{
    "a": {
      "b": [
          { 
            "name": "admin",
            "appconfig": {
                "test1": true,
                "test2": false
            }
          }
        ]
    },
    "c": "asdasd"
  }
  ' | ConvertFrom-Json
  
  $Json2 = '{
    "a": {
        "b": [
            { 
              "name": "admin",
              "appconfig": {
                  "test1": false
              }
            }
          ]
    }
  }
  ' | ConvertFrom-Json

merger $Json1 $Json2

{
  "a": {
    "b": [
      {
        "name": "admin",
        "appconfig": {
          "test1": false
        }
      }
    ]
  },
  "c": "asdasd"
}

test2 is gone!

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

老子叫无熙 2025-01-30 06:11:00

我还没有足够的代表来发布常规评论,因此我必须将其发布为答案:

我在 to 另一个问题,它完成了您的要求。此答案的优点是它不依赖于导入单独的模块。

同一问题中还有另一个答案,该答案提供了更通用模块的链接,该模块提供了不同类型的合并(左JOIN,INNER JOIN等)在这里,链接到在这里。但是,一位评论员说,它与PowerShell 7.0不起作用。

I don't have enough rep to post general comments yet, so I'll have to post it as an answer:

I tested the code in this answer to another question, and it did what you asked. The advantage of this answer is that it doesn't depend on importing a separate module.

There's another answer in the same question that provides link to a more general module that provides for different types of merges (Left Join, Inner Join, etc.) here, which links to here. However, one commenter said that it didn't work with powershell 7.0.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文