Hello Rakesh Singh,
Can you please execute the below PowerShell script
The script below retrieves details of all resource names, policy definition names, resource groups, subscription names, and locations from all Azure subscriptions.
# Login with Connect-AzAccount if not using Cloud Shell
Connect-AzAccount
# Initialize an empty array for storing non-compliant resources
$vmArray = @()
# Get all Azure subscriptions
$azureSubscriptions = Get-AzSubscription
# Loop through each subscription
foreach ($subscription in $azureSubscriptions) {
# Set the Azure context to the current subscription
Set-AzContext -SubscriptionId $subscription.Id
# Get non-compliant resources for the current subscription
$nonCompliantResources = Get-AzPolicyState | Where-Object { $_.ComplianceState -eq "NonCompliant" }
# Output the count of non-compliant resources for the current subscription
Write-Host "Subscription: $($subscription.Name) - Non-Compliant Resources: $($nonCompliantResources.Count)"
# Retrieve and process non-compliant resources
foreach ($resource in $nonCompliantResources) {
$resourceName = $resource.resourceId.Split('/')[-1]
$resourceType = $resource.resourceType
$complianceState = $resource.complianceState
$resourceGroup = $resource.resourceGroup
$resourceLocation = $resource.resourceLocation
$policyDefinitionName = $resource.PolicyDefinitionReferenceId
# Store resource details in an object
$vmArray += New-Object PSObject -Property @{
ResourceType = $resourceType
SubscriptionName = $subscription.Name
ComplianceState = $complianceState
ResourceName = $resourceName
ResourceLocation = $resourceLocation
PolicyDefinitionName = $policyDefinitionName
ResourceGroup = $resourceGroup
}
}
}
# Export the results to a CSV file
$vmArray | Export-CSV -Path ".\compliance.csv" -NoTypeInformation
Write-Host "Compliance report exported to compliance.csv"
Output For Reference:
Feel free to reach out if you have any further questions or need additional information—I’m happy to assist!
Please provide your valuable comments
Please do not forget to "Accept the answer” and “upvote it” wherever the information provided helps you, this can be beneficial to other community members.it would be greatly appreciated and helpful to others.