Quick Code – Install AMA and Assign a DCR with PowerShell

Happy Holidays! Here’s a quick post to share some code that will inventory Azure VMs, install the AMA if necessary, and then assign a DCR to the VM.

# Ensure you're logged in to Azure
Connect-AzAccount

# Define the Data Collection Rule (DCR) resource ID
$dcrResourceId = "<Your-DCR-Resource-ID>"

# Get all VMs in the subscription
$vms = Get-AzVM

# Use ForEach-Object with -Parallel to process VMs concurrently
$vms | ForEach-Object -Parallel {
    $vm = $_
    $osType = $vm.StorageProfile.OsDisk.OsType
    $extensionName = if ($osType -eq "Windows") { "AzureMonitorWindowsAgent" } else { "AzureMonitorLinuxAgent" }
    $extensionPublisher = "Microsoft.Azure.Monitor"
    $vmResourceId = "/subscriptions/$using:vm.SubscriptionId/resourceGroups/$using:vm.ResourceGroupName/providers/Microsoft.Compute/virtualMachines/$using:vm.Name"

    try {
        # Check if the Azure Monitor Agent extension is installed
        $amaExtension = Get-AzVMExtension -ResourceGroupName $using:vm.ResourceGroupName -VMName $using:vm.Name -Name $extensionName -ErrorAction SilentlyContinue

        if (-not $amaExtension) {
            try {
                # Install the Azure Monitor Agent extension
                Set-AzVMExtension -ResourceGroupName $using:vm.ResourceGroupName -VMName $using:vm.Name -Name $extensionName -Publisher $extensionPublisher -ExtensionType $extensionName -TypeHandlerVersion "1.0" -Location $using:vm.Location
                Write-Host "Installed Azure Monitor Agent on $($using:vm.Name)"
            } catch {
                Write-Host "Failed to install Azure Monitor Agent on $($using:vm.Name): $_"
            }
        } else {
            Write-Host "Azure Monitor Agent is already installed on $($using:vm.Name)"
        }
    } catch {
        Write-Host "Error checking Azure Monitor Agent on $($using:vm.Name): $_"
    }

    try {
        # Assign the DCR to the VM
        $settings = @{ "dataCollectionRuleResourceIds" = @($using:dcrResourceId) }
        Set-AzVMExtension -ResourceGroupName $using:vm.ResourceGroupName -VMName $using:vm.Name -Name "AzureMonitorVmExtension" -Publisher $extensionPublisher -ExtensionType $extensionName -Settings $settings -Location $using:vm.Location
        Write-Host "Assigned DCR to $($using:vm.Name)"
    } catch {
        Write-Host "Failed to assign DCR to $($using:vm.Name): $_"
    }
} -ThrottleLimit 5 # Adjust the ThrottleLimit as necessary