I'm trying to write a script which recursively deletes Azure Management Groups. Azure Management Groups can have up to 6 levels of hierarchy. You cannot delete the top level management group unless all the children have been deleted first.
$toplevelgroup = Get-AzManagementGroup -GroupName 'MyTopLevelGroup' -Expand -Recurse
Returns a 'PSManagementGroup' object. If it has child management groups you can access them like this:
$toplevelgroup.Children
which returns something like this:
Type : /providers/Microsoft.Management/managementGroups
Id : /providers/Microsoft.Management/managementGroups/2
Name : 2
DisplayName : 2
Children : 3
Note Children : 3 is actually because the next level down mgmt group is called '3'.
My script would need to
- Get the Top-Level Mgmt Group Object based on the parameter of the mgmt group name passed.
- Test how many levels of child mgmt groups there are
- Loop through the lowest level of management groups first and delete them, then move on to the next parent level and delete those and repeat until the top level group is also deleted.
What I originally wrote is dumb and only works if there are 3 level of management group so I'm looking for some pointer to help make this script more robust.
# Delete All Management Groups
$toplevelgroup = Get-AzManagementGroup -GroupName 'MyTopLevelGroup' -Expand -Recurse
$children = $toplevelgroup.Children
$grandchildren = $toplevelgroup.Children.Children
foreach ($grandchild in $grandchildren) {
Remove-AzManagementGroup -GroupName $grandchild.Name
}
foreach ($child in $children){
Remove-AzManagementGroup -GroupName $child.Name
}
Remove-AzManagementGroup -GroupName $toplevelgroup.Name
Docs: