param( $dirName = 'C:\Infrastructure\Azure-RBAC-Exceptions', $environment = 'DEV' ) Set-StrictMode -Version Latest $ErrorActionPreference = "Stop" $InformationPreference = "Continue" # Initialize a collection for error findings $errorFindings = [System.Collections.Concurrent.ConcurrentBag[string]]::new() # Get all the subscription folders for the given environment $Subscriptionfolders = Get-ChildItem -Path $dirName -Directory if ($environment -eq 'DEV') { $subscriptions = $Subscriptionfolders | Where-Object { $_.Name -like "AGDEV_*" -and $_.Name -notlike "*IAM*" } } else { $subscriptions = $Subscriptionfolders | Where-Object { $_.Name -like "AG_*" -and $_.Name -notlike "*IAM*" } } # Validate each subscription in parallel $allErrors = $subscriptions | ForEach-Object -Parallel { $SubscriptionName = $_.Name Select-AzSubscription -Subscription $SubscriptionName -Verbose $subscriptionFolder = Join-Path -Path $using:dirName -ChildPath $SubscriptionName $localErrors = @() $resourceGroups = Get-ChildItem -Path $subscriptionFolder -File foreach ($resourceGroupFile in $resourceGroups) { $resourceGroup = [System.IO.Path]::GetFileNameWithoutExtension($resourceGroupFile.Name) try { $resourceGroupExists = Get-AzResourceGroup -Name $resourceGroup -ErrorAction Stop } catch { $localErrors += "Resource group '$resourceGroup' does not exist." } $roleAssignments = Get-Content -Path $resourceGroupFile.FullName | ConvertFrom-Json foreach ($roleAssignment in $roleAssignments) { try { $validRole = Get-AzRoleDefinition -Name $roleAssignment.RoleDefinitionName -ErrorAction SilentlyContinue } catch { $localErrors += "Role definition '$($roleAssignment.RoleDefinitionName)' does not exist." continue } $ADObject = $null try { $ADObject = Get-AzADServicePrincipal -ObjectId $roleAssignment.ObjectId -ErrorAction Stop } catch { try { $ADObject = Get-AzADGroup -ObjectId $roleAssignment.ObjectId -ErrorAction Stop } catch { try { $ADObject = Get-AzADUser -ObjectId $roleAssignment.ObjectId -ErrorAction Stop } catch { $localErrors += "Object ID '$($roleAssignment.ObjectId)' for '$($roleAssignment.DisplayName)' does not exist in Active Directory." continue } } } if ($ADObject -and $ADObject.DisplayName -ne $roleAssignment.DisplayName) { $localErrors += "Display name mismatch for Object ID '$($roleAssignment.ObjectId)': expected '$($roleAssignment.DisplayName)', found '$($ADObject.DisplayName)'." } } } return $localErrors } -ThrottleLimit 4 # Add all errors to the concurrent bag $allErrors | ForEach-Object { $errorFindings.Add($_) } if ($errorFindings.Count -gt 0) { $errorFindings | ForEach-Object { Write-Error $_ } }