param([Parameter(Mandatory)][string]$SubscriptionId)
$ErrorActionPreference='Stop'
$rg='rg-machine-configuration-deep-dive-we';$loc='westeurope';$root=Split-Path -Parent $PSScriptRoot;$private=Join-Path $root '.private'
$context=Get-Content -Raw (Join-Path $private 'runtime-context.json')|ConvertFrom-Json
$dcrId="/subscriptions/$SubscriptionId/resourceGroups/$rg/providers/Microsoft.Insights/dataCollectionRules/dcr-machine-config-events-we"
$body=@{location=$loc;properties=@{dataSources=@{windowsEventLogs=@(@{name='WorkshopEvents';streams=@('Microsoft-Event');xPathQueries=@("Application!*[System[Provider[@Name='AzureWorkshopzMachineConfiguration']]]",'System!*[System[(Level=1 or Level=2 or Level=3)]]')})};destinations=@{logAnalytics=@(@{workspaceResourceId=$context.WorkspaceResourceId;name='workshopWorkspace'})};dataFlows=@(@{streams=@('Microsoft-Event');destinations=@('workshopWorkspace')})}}
$path=Join-Path $private 'dcr.json';$body|ConvertTo-Json -Depth 20|Set-Content $path
az rest --method put --url "https://management.azure.com$dcrId`?api-version=2023-03-11" --body "@$path" --only-show-errors -o none
foreach($vm in 'vm-mc-ws2022-we','vm-mc-ws2025-we'){$vmId=az vm show -g $rg -n $vm --query id -o tsv --only-show-errors;$p=Join-Path $private "dcra-$vm.json";@{properties=@{dataCollectionRuleId=$dcrId}}|ConvertTo-Json -Depth 5|Set-Content $p;az rest --method put --url "https://management.azure.com$vmId/providers/Microsoft.Insights/dataCollectionRuleAssociations/dcra-machine-config?api-version=2023-03-11" --body "@$p" --only-show-errors -o none}
'DCR and VM associations configured.'
