Hi @Ankit Sharma
Please find the below altered script, and the out put attached
# Login to Azure
Connect-AzAccount
# Get all available subscriptions
$subscriptions = Get-AzSubscription
# Create an empty list to store the final report data
$finalReportData = @()
# Loop through each subscription
foreach ($subscription in $subscriptions) {
# Set the subscription context
Set-AzContext -SubscriptionId $subscription.Id
# Get the policy compliance state for all resources in the current subscription
$policyComplianceData = Get-AzPolicyState
# Get the associated policies and initiatives
$policyDefinitions = Get-AzPolicyDefinition
$initiatives = Get-AzPolicySetDefinition
# Loop through each policy compliance data entry
foreach ($policy in $policyComplianceData) {
# Get Resource Name if available (sometimes this can be inside the ResourceId property)
$resourceName = $policy.ResourceId -split '/' | Select-Object -Last 1
# Find the corresponding policy definition or initiative for the compliance state
$policyDefinition = $policyDefinitions | Where-Object { $_.Id -eq $policy.PolicyDefinitionId }
$initiativeDefinition = $initiatives | Where-Object { $_.Id -eq $policy.PolicyDefinitionId }
# Determine if it is an initiative or policy definition
$policyType = ""
$policyName = ""
$policyId = ""
if ($policyDefinition) {
$policyType = "Policy Definition"
$policyName = $policyDefinition.DisplayName
$policyId = $policyDefinition.Id
} elseif ($initiativeDefinition) {
$policyType = "Initiative"
$policyName = $initiativeDefinition.DisplayName
$policyId = $initiativeDefinition.Id
}
# Add the data for this policy to the final report
$finalReportData += New-Object PSObject -property @{
SubscriptionName = $subscription.Name
ComplianceState = $policy.ComplianceState
ResourceGroup = $policy.ResourceGroup
ResourceName = $resourceName
ResourceType = $policy.ResourceType
ResourceLocation = $policy.ResourceLocation
Timestamp = $policy.Timestamp
ResourceId = $policy.ResourceId
IsCompliant = $policy.IsCompliant
PolicyDefinitionAction = $policy.PolicyDefinitionAction
PolicyType = $policyType
PolicyName = $policyName
PolicyId = $policyId
}
}
}
# Ensure the directory for saving the CSV exists
$directoryPath = "C:\Reports"
if (-not (Test-Path -Path $directoryPath)) {
New-Item -ItemType Directory -Path $directoryPath
}
# Export the final report to CSV
$finalReportData | Export-Csv -Path "C:\Users\v-ashkotnana\policy_compliance_report1.csv" -NoTypeInformation
Change the path to your path
Below is the output, change the path
Hope this answers your question. Let us know if you need any further assistance
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.