Azure / enterprise-azure-policy-as-code

Enterprise-ready Azure Policy-as-Code (PaC) solution (includes Az DevOps pipeline)
https://azure.github.io/enterprise-azure-policy-as-code/
MIT License
437 stars 243 forks source link

fix null error on $rawMetadata.createdOn #716

Closed AzureStackNerd closed 3 months ago

AzureStackNerd commented 3 months ago

Exporting the policies raised a bunch of errors around ($rawMetadata.createdOn).ToString("s"). Since I don't like errors I wrote a fix for it.

Error

image

File affected

Export-AzPolicyResources.ps1:

Fix

$rowObj.lastChange = if ($null -ne $rawMetadata.createdOn) { ($rawMetadata.createdOn).ToString("s") } else { "n/a" }
AzureStackNerd commented 3 months ago

Furthermore, I have the following partly related error when exporting policies:

Error

image

Cause

After some research I found out that the line for exporting $allRows to CSV fails because principalId is empty and it breaks.

Fix

If $rawMetadata.updatedBy is empty, do not automatically assume that $rawMetadata.createdBy is not empty

            if ($null -ne $rawMetadata.updatedBy) {
                $rowObj.principalId = $rawMetadata.updatedBy
                $rowObj.lastChange = if ($null -ne $rawMetadata.updatedOn) { ($rawMetadata.updatedOn).ToString("s") } else { "n/a" }
            }
            elseif ($null -ne $rawMetadata.createdBy) {
                $rowObj.principalId = $rawMetadata.createdBy
                $rowObj.lastChange = if ($null -ne $rawMetadata.createdOn) { ($rawMetadata.createdOn).ToString("s") } else { "n/a" }
            }
            else {
                $rowObj.principalId = "n/a"
                $rowObj.lastChange = if ($null -ne $rawMetadata.createdOn) { ($rawMetadata.createdOn).ToString("s") } else { "n/a" }
            }
AzureStackNerd commented 3 months ago

I made a booboo earlier with updatenOn and createdOn. fixed

AzureStackNerd commented 3 months ago

This code is now working errorless for me, and the policy-ownership.csv file now contains all my 1765 records.