You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PowerShell读取两组JSON匹配Name字段更新标签值的实现方案

PowerShell 同步两组Azure资源JSON标签的实现方案

实现代码

你可以直接复用以下完整脚本,按需修改文件路径即可:

# 1. 加载两组JSON数据
# 替换为你自己的源资源组JSON文件路径
$sourceRes = Get-Content -Path "C:\xxx\source-resource.json" | ConvertFrom-Json
# 替换为你自己的目标资源组JSON文件路径
$targetRes = Get-Content -Path "C:\xxx\target-resource.json" | ConvertFrom-Json

# 2. 构造源资源的名称索引哈希表,提升匹配效率
$sourceIndex = @{}
foreach ($item in $sourceRes) {
    $sourceIndex[$item.Name] = $item
}

# 3. 遍历目标资源匹配同名资源更新标签
foreach ($item in $targetRes) {
    if ($sourceIndex.ContainsKey($item.Name)) {
        $item.Tags = $sourceIndex[$item.Name].Tags
    }
}

# 4. 导出更新后的目标资源JSON
# 替换为你要保存的新文件路径,Depth参数根据你JSON的嵌套层级调整,避免属性丢失
$targetRes | ConvertTo-Json -Depth 10 | Out-File -Path "C:\xxx\updated-target-resource.json" -Encoding UTF8

可选拓展:直接同步标签到Azure实际资源

如果你不需要导出JSON,要直接把更新后的标签写入Azure目标资源组的真实资源,可在第三步的匹配逻辑中追加资源更新命令:

foreach ($item in $targetRes) {
    if ($sourceIndex.ContainsKey($item.Name)) {
        $newTags = $sourceIndex[$item.Name].Tags
        $item.Tags = $newTags
        # 直接更新Azure资源标签
        Set-AzResource -ResourceId $item.Id -Tag $newTags -Force
    }
}

注意:执行更新Azure资源的命令前,请确保你已经通过Connect-AzAccount登录了正确的Azure租户,并且拥有目标资源组的写入权限。

内容的提问来源于stack exchange,提问作者MouIdri

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.17 13:06:05