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

如何通过PowerShell保留指定Azure LAW并移除VM上其余关联LAW

Azure VM批量保留指定Log Analytics工作区脚本方案

核心逻辑

批量遍历目标虚拟机,获取其当前关联的所有Log Analytics工作区(LAW),对比预先定义的保留ID列表,自动移除不在列表内的LAW关联,无需手动枚举待删除的LAW ID。

完整PowerShell脚本

# -------------------------- 配置参数 --------------------------
# 替换为你需要保留的Log Analytics工作区完整资源ID
$allowedLawIds = @(
    "/subscriptions/xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/rg-demo/providers/Microsoft.OperationalInsights/workspaces/law-prod-01",
    "/subscriptions/xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx/resourceGroups/rg-demo/providers/Microsoft.OperationalInsights/workspaces/law-prod-02"
)

# 指定处理范围:可按需选择以下任一方式
# 方式1:处理指定订阅下所有VM
# Set-AzContext -Subscription "你的订阅ID/名称"
# $targetVMs = Get-AzVM

# 方式2:处理指定资源组下的VM
$targetVMs = Get-AzVM -ResourceGroupName "rg-demo"

# -------------------------- 执行批量处理 --------------------------
foreach ($vm in $targetVMs) {
    Write-Host "`n开始处理VM: $($vm.Name)" -ForegroundColor Cyan

    # 获取当前VM关联的监控扩展(区分Windows/Linux)
    $monitorExtension = Get-AzVMExtension -ResourceGroupName $vm.ResourceGroupName -VMName $vm.Name | Where-Object {
        $_.Publisher -eq "Microsoft.EnterpriseCloud.Monitoring" -and 
        $_.Name -in ("MicrosoftMonitoringAgent", "OmsAgentForLinux")
    }

    if (-not $monitorExtension) {
        Write-Host "该VM未关联任何Log Analytics工作区,跳过" -ForegroundColor Gray
        continue
    }

    # 解析当前关联的LAW ID
    $currentLawId = ($monitorExtension.Settings | ConvertFrom-Json).workspaceId

    # 判断是否需要移除
    if ($currentLawId -notin $allowedLawIds) {
        try {
            # 卸载监控扩展以解除LAW关联
            Remove-AzVMExtension -ResourceGroupName $vm.ResourceGroupName -VMName $vm.Name `
                -Name $monitorExtension.Name -Force -ErrorAction Stop
            Write-Host "已移除VM与非保留LAW的关联" -ForegroundColor Green
        }
        catch {
            Write-Host "处理失败: $_" -ForegroundColor Red
        }
    } else {
        Write-Host "关联的LAW在保留列表内,无需操作" -ForegroundColor Green
    }
}

关键注意事项

  • 需提前安装Az模块:执行Install-Module -Name Az -AllowClobber -Scope CurrentUser完成安装
  • 执行前通过Connect-AzAccount登录Azure,多订阅场景需用Set-AzContext切换目标订阅
  • 脚本中MicrosoftMonitoringAgent对应Windows VM,OmsAgentForLinux对应Linux VM,需根据实际环境匹配
  • 建议先在测试VM上验证逻辑,再批量执行

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 23:37:45