Reputation: 11
'
subscriptionId = 'abc'
$nonCompliantPolicies = Get-AzPolicyState -SubscriptionId $subscriptionId
# Define a custom object for each non-compliant resource
$customObjects = $nonCompliantPolicies | ForEach-Object {
[PSCustomObject]@{
PolicyName = $_.PolicyDefinitionName
ComplianceState = $_.ComplianceState
ResourceType = $_.ResourceType
ResourceGroup = $_.ResourceGroup
SubscriptionId = $_. subscriptionId
IsCompliant = $_.IsCompliant
PolicyAssignmentScope =$_.PolicyAssignmentScope
}
}
# Export the custom objects to a CSV file
$customObjects | Format-Table -AutoSize
'
Policy name is generating GUID value but i need descriptive name kinldy provide a solution as how i can modify my code to get descriptive name of the policies rather than guid id
Upvotes: 1
Views: 185
Reputation: 1308
get-policy state not returning correct display name instead returning guid
The Get-AzPolicyState
command will display the policy definition name as a GUID instead of the descriptive name
To get the names using the policy definition GUID, you can use the script below to retrieve the policy definition names from the GUID.
$subId = "SUB_ID"
$NonCompliantPolicies = Get-AzPolicyState -SubscriptionId $subscriptionId
$customObjects = @()
foreach ($policy in $nonCompliantPolicies) {
$policyDefName = $policy.PolicySetDefinitionName
$policyDefinitions = Get-AzPolicyDefinition -Name $policyDefName
$customObjects += [PSCustomObject]@{
PolicyName = $policyDefinitions.DisplayName
ComplianceState = $policy.ComplianceState
ResourceType = $policy.ResourceType
ResourceGroup = $policy.ResourceGroup
SubscriptionId = $policy.SubscriptionId
IsCompliant = $policy.IsCompliant
PolicyAssignmentScope = $policy.PolicyAssignmentScope
}
}
$customObjects | Format-Table -AutoSize
$customObjects | Export-Csv -Path "NonCompliantPoliciesreport.csv" -NoTypeInformation
Note: If the script above throws an error when executing it locally, please run it in Azure Cloud Shell.
Output
Excel Output
Upvotes: 0
Reputation: 1521
$subscriptionId = "xxxx-xxxx-xxxx-xxxx-xxxx"
$policyStates = Get-AzPolicyState -SubscriptionId $subscriptionId
# $nonCompliantPolicies
$customObjects = $policyStates | ForEach-Object {
[PSCustomObject]@{
PolicyDefinitionName = $(Get-AzPolicyDefinition -Id $_.PolicyDefinitionId).Properties.DisplayName
PolicyAssignmentName = $(Get-AzPolicyAssignment -Id $_.PolicyAssignmentId).Properties.DisplayName
ComplianceState = $_.ComplianceState
ResourceType = $_.ResourceType
ResourceGroup = $_.ResourceGroup
SubscriptionId = $_. subscriptionId
IsCompliant = $_.IsCompliant
PolicyAssignmentScope =$_.PolicyAssignmentScope
}
}
$customObjects | Format-Table -AutoSize | Out-File xx.txt
Policy definition name
may be different from policy assignment name
sometimes, so need also include both to show more infomations.
Upvotes: 0