How can I write a PowerShell script to create DCR rules, apply to VMs of subscriptions, and install the latest AMA agent?
Here is a PowerShell script to create a DCR rule and apply the rule to all VM's in Subscription.
Connect-AzAccount -Subscription "Subscription-Name" Install-Module Az.Monitor Import-Module Az.Monitor $resourceGroup = "venkattests-resources" $dcrRule = New-AzDataCollectionRule -Location "eastus" -ResourceGroupName "Resource-Group-Name" -RuleName "Install-Agent" -RuleFile "DCR.json" $dcr = Get-AzDataCollectionRule -ResourceGroupName $resourceGroup -RuleName $dcrRule.Name #Get all VM's in Subscription $Vms = Get-AzVM foreach ($vm in $Vms) { $vmId = $vm.Id $VmName = $vm.Name $dcrname = $DcrRule.Name Write-Host "Applying DCR Rule Name: $dcrname to VM Name: $VmName " #Apply the DCR to all VM's in Subscription New-AzDataCollectionRuleAssociation -TargetResourceId $vmId -AssociationName "DCRRule" -RuleId $dcr.Id } }
I have followed this Ms-Doc to create Data Collection Rule
DCR.json
{ "properties": { "dataSources": { "performanceCounters": [ { "streams": [ "Microsoft-InsightsMetrics" ], "scheduledTransferPeriod": "PT1M", "samplingFrequencyInSeconds": 10, "counterSpecifiers": [ "\\Processor Information(_Total)\\% Processor Time" ], "name": "perfCounter01" } ] }, "destinations": { "azureMonitorMetrics": { "name": "azureMonitorMetrics-default" } }, "dataFlows": [ { "streams": [ "Microsoft-InsightsMetrics" ], "destinations": [ "azureMonitorMetrics-default" ] } ] } }
Output:

Reference: Create data collection rule association & Create a data collection rule.