如何通过PowerShell为Azure Windows VM配置AMA代理与DCR规则?
使用PowerShell自动化部署Azure Monitor Agent(AMA)并配置DCR规则
前置准备
- 安装最新版Az PowerShell模块,重点确保
Az.Monitor和Az.Compute模块已更新 - 登录Azure账户:
Connect-AzAccount - 切换至目标订阅:
Set-AzContext -Subscription "你的订阅ID/名称"
步骤1:创建数据收集规则(DCR)
先定义DCR的配置模板(以下示例针对Windows VM收集性能计数器和事件日志),再通过PowerShell完成创建:
# 配置基础参数 $resourceGroupName = "你的资源组名称" $dcrName = "WinVM-AMA-DCR" $location = "eastus" # 建议与目标VM同区域 $workspace = Get-AzOperationalInsightsWorkspace -ResourceGroupName $resourceGroupName -Name "你的Log Analytics工作区名称" # 构建DCR的JSON配置 $dcrJson = @" { "properties": { "dataSources": { "performanceCounters": [ { "name": "WindowsPerfCounters", "streams": ["Microsoft-Perf"], "scheduledTransferPeriod": "PT1M", "counterSpecifiers": [ "\\Processor(_Total)\\% Processor Time", "\\Memory\\Available MBytes", "\\LogicalDisk(_Total)\\% Free Space" ] } ], "windowsEventLogs": [ { "name": "WindowsEventLogs", "streams": ["Microsoft-Event"], "xPathQueries": [ "System![System[(Level=1 or Level=2 or Level=3)]]", "Application![System[(Level=1 or Level=2 or Level=3)]]" ] } ] }, "destinations": { "logAnalytics": [ { "workspaceResourceId": "$($workspace.Id)", "name": "LogAnalyticsWorkspace" } ] }, "dataFlows": [ { "streams": ["Microsoft-Perf", "Microsoft-Event"], "destinations": ["LogAnalyticsWorkspace"] } ] }, "location": "$location" } "@ # 创建DCR资源 New-AzResource -ResourceGroupName $resourceGroupName ` -ResourceType "Microsoft.Insights/dataCollectionRules" ` -Name $dcrName ` -Property $dcrJson ` -Force
步骤2:将DCR关联到目标Windows虚拟机
遍历订阅内的Windows VM(可按需过滤范围),创建数据收集关联(DCRA):
# 获取订阅内所有Windows VM(可添加Where-Object过滤特定资源组/标签) $windowsVMs = Get-AzVM | Where-Object {$_.StorageProfile.OsDisk.OsType -eq "Windows"} $dcrResourceId = "/subscriptions/你的订阅ID/resourceGroups/$resourceGroupName/providers/Microsoft.Insights/dataCollectionRules/$dcrName" foreach ($vm in $windowsVMs) { $dcraName = "$($vm.Name)-DCR-Assoc" # 创建VM与DCR的关联 New-AzResource -ResourceGroupName $vm.ResourceGroupName ` -ResourceType "Microsoft.Insights/dataCollectionRuleAssociations" ` -Name "$($vm.Name)/$dcraName" ` -Property @{ dataCollectionRuleId = $dcrResourceId } ` -Force }
步骤3:安装Azure Monitor Agent到Windows VM
通过Azure VM扩展的方式安装Windows版AMA:
foreach ($vm in $windowsVMs) { Set-AzVMExtension -ResourceGroupName $vm.ResourceGroupName ` -VMName $vm.Name ` -Name "AzureMonitorWindowsAgent" ` -Publisher "Microsoft.Azure.Monitor" ` -Type "AzureMonitorWindowsAgent" ` -TypeHandlerVersion "1.0" ` -AutoUpgradeMinorVersion $true ` -Force }
部署验证
- 检查DCR状态:
Get-AzDataCollectionRule -ResourceGroupName $resourceGroupName -Name $dcrName - 检查VM扩展状态:
Get-AzVMExtension -ResourceGroupName $vm.ResourceGroupName -VMName $vm.Name -Name "AzureMonitorWindowsAgent" - 检查DCR关联状态:
Get-AzDataCollectionRuleAssociation -ResourceId $vm.Id
内容的提问来源于stack exchange,提问作者swadesh
相关产品推荐
相关产品推荐

