Powershell - 以递归方式查找和更新命名对象属性的所有实例 [英] Powershell - Find and update all instances of named object property recursively

查看:65
本文介绍了Powershell - 以递归方式查找和更新命名对象属性的所有实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 powershell 更新大型导出 JSON 文件中名为 sourceList 的属性的所有实例,但是 JSON 的结构与每次导出不一致,该属性出现在不同的位置深度:

I need to use powershell to update all instances of a property called sourceList in a large exported JSON file, however the structure of the JSON is not consistent with each export, with the property occuring at various depths:

JSON 结构示例

{
    "rows": [
        {
            "controls": [
                {
                    "properties": {
                        "sourceList": "I NEED TO CHANGE THIS"
                    }
                }
            ]
        },
        {
            "controls": [
                {
                    "properties": {
                        "rows": [
                            {
                                "controls": [
                                    {
                                        "properties": {
                                            "sourceList": "ALSO THIS, BUT IT'S MUCH DEEPER"
                                        }
                                    }
                                ]
                            }
                        ]
                    }
                }
            ]
        }
    ]
}

JSON 文件来自表单构建工具,因此不同的表单设计(例如将字段放入组容器中)可能会导致深度发生巨大变化.

The JSON file is from a form building tool, so different form designs (e.g. putting fields in group container) can cause the depth to change drastically.

$formObj = Get-Content -Raw -Path $form | ConvertFrom-Json
# Find and update all instances of sourceList
$formObj | ConvertTo-Json -Depth 100 | Set-Content $form

与 JSON 之间的实际转换工作正常,我已经成功更改了一些其他具有可靠结构的属性,我的问题是查找和更新命名属性,但无法知道它将在什么深度发生.

The actual conversion to and from JSON works fine, and I've successfully changed some other properties that have a reliable structure, my issue is finding and updating a named property with no way of knowing at what depth it will occur.

推荐答案

为什么不这样做...

Select-String -Path '.\FormTool.txt' -Pattern 'sourceList' -Context 0
# Results
<#
FormTool.txt:7:                        "sourceList": "I NEED TO CHANGE THIS"
FormTool.txt:21:                                            "sourceList": "ALSO THIS, BUT IT'S MUCH DEEPER"
#>

然后在行号或字符串匹配处修改.

Then modify at the line number or string match.

(Select-String -Path '.\FormTool.txt' -Pattern 'sourceList' -Context 0) -replace '\:\s".*', ': "Repalced with this stuff"'
# Results
<#
D:\Scripts\FormTool.txt:7:                        "sourceList": "Repalced with this stuff"
D:\Scripts\FormTool.txt:21:                                            "sourceList": "Repalced with this stuff"
#>

这篇关于Powershell - 以递归方式查找和更新命名对象属性的所有实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆