Hello Chris Pretorius
Please use below updated script to get the policies list at management scope.
# Login if needed
Connect-AzAccount
# Initialize array
$vmArray = @()
# Get all management groups
$mgList = Get-AzManagementGroup
foreach ($mg in $mgList) {
$mgName = $mg.Name
Write-Host "Processing Management Group: $mgName"
# Get non-compliant resources at MG level
$nonCompliantResources = Get-AzPolicyState -ManagementGroupName $mgName | Where-Object { $_.ComplianceState -eq "NonCompliant" }
Write-Host "Non-Compliant Resources in $mgName: $($nonCompliantResources.Count)"
foreach ($resource in $nonCompliantResources) {
$resourceName = $resource.resourceId.Split('/')[-1]
$resourceType = $resource.resourceType
$complianceState = $resource.complianceState
$resourceGroup = $resource.resourceGroup
$resourceLocation = $resource.resourceLocation
$policyDefinitionName = $resource.PolicyDefinitionReferenceId
$PolicyAssignmentName = $resource.PolicyAssignmentName
$InitiativeId = $resource.PolicySetDefinitionId
$InitiativeName = $resource.PolicySetDefinitionName
$subscriptionId = $resource.SubscriptionId
# Get Initiative Display Name
$InitiativeDisplayName = $null
if ($InitiativeId) {
$initiativeDetails = Get-AzPolicySetDefinition -Id $InitiativeId -ErrorAction SilentlyContinue
if ($initiativeDetails) {
$InitiativeDisplayName = $initiativeDetails.Properties.DisplayName
}
}
# Store details
$vmArray += New-Object PSObject -Property @{
ManagementGroupName = $mgName
PolicyDefinitionName = $policyDefinitionName
InitiativeDisplayName = $InitiativeDisplayName
ComplianceState = $complianceState
SubscriptionId = $subscriptionId
ResourceGroup = $resourceGroup
ResourceName = $resourceName
ResourceType = $resourceType
ResourceLocation = $resourceLocation
}
}
}
# Export to CSV
$vmArray | Sort-Object ManagementGroupName, PolicyDefinitionName, InitiativeDisplayName, ComplianceState, SubscriptionId, ResourceGroup, ResourceName, ResourceType, ResourceLocation | Export-CSV -Path ".\mg-compliance-all.csv" -NoTypeInformation
Please let me know if you face any challenge here, I can help you to resolve this issue further
If the comment was helpful, please click "Upvote"