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

如何使用PowerShell下载Azure资源组中所有资源的JSON文件?

批量导出Azure资源组资源JSON用于变更验证

我正尝试通过PowerShell将指定Azure资源组中的所有资源导出为JSON格式,用于部署后对比验证变更,但不同资源类型对应不同命令,且API版本各异,导致批量解析难度大。以下是我正在使用的脚本版本,同时我也考虑过azure.resources.com的AzCopy方案,没有明确偏好,当前文件是手动从azure.resources.com复制的。

现有PowerShell脚本(已翻译注释)

# 提示用户输入Azure资源组名称
$resourceGroup = Read-Host "请输入Azure资源组名称"

# 提示用户指定文件路径后缀为"old"或"new"
$fileSuffix = Read-Host "请指定文件路径后缀,输入'old'或'new'"

# 验证用户输入的后缀是否合法
if ($fileSuffix -notin "old", "new") {
    Write-Host "后缀无效,请输入'old'或'new'。"
    return
}

# 定义保存JSON文件的根文件夹
$folderName = $resourceGroup

# 如果文件夹不存在则创建
if (-not (Test-Path -Path $folderName -PathType Container)) {
    New-Item -Path $folderName -ItemType Directory
}

# 获取指定资源组中的所有资源
$resources = Get-AzResource -ResourceGroupName $resourceGroup

if ($resources) {
    foreach ($resource in $resources) {
        # 提取资源提供者信息
        $providerNamespace = $resource.ResourceProviderNamespace
        $resourceType = $resource.ResourceType
        $apiVersion = $resource.ApiVersion
        $resourceName = $resource.Name

        # 构造带指定后缀的文件路径
        $filePath = "$folderName\$providerNamespace\$resourceType\$fileSuffix\$resourceName-$apiVersion.json"

        # 如果提供者命名空间、资源类型及后缀对应的文件夹不存在则创建
        if (-not (Test-Path -Path "$folderName\$providerNamespace\$resourceType\$fileSuffix" -PathType Container)) {
            New-Item -Path "$folderName\$providerNamespace\$resourceType\$fileSuffix" -ItemType Directory -Force
        }

        # 使用Azure CLI获取资源JSON并保存到指定路径
        az resource show --resource-group $resourceGroup --name $resourceName --resource-type $resourceType --api-version $apiVersion --query '{Name:name, Properties:properties}' --output json | Set-Content -Path $filePath

        # 检查资源是否成功下载
        if ($LASTEXITCODE -eq 0) {
            Write-Host "资源JSON已成功保存到 $filePath"
        } else {
            Write-Host "下载资源 $resourceName 的JSON失败"
        }
    }
} else {
    Write-Host "资源组 '$resourceGroup' 中未找到任何资源"
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.09 16:52:49