Powershell Azure UserGroups Removal

 # Requires Microsoft.Graph module: Install-Module Microsoft.Graph -Scope CurrentUser


# --- Configuration ---

# <<<<< IMPORTANT: REPLACE WITH YOUR TEST TENANT ID >>>>>

$tenantId = "515FF807-4698-4D87-8380-98D33D7BE5XX" 

$baseGroupDisplayNamePrefix = "HyperAggroTestGroup" # This matches the prefix used in the aggressive scripts


Write-Host "Starting cleanup: Deleting all groups with DisplayName starting with '$baseGroupDisplayNamePrefix' in Tenant: $tenantId"

Write-Host "-----------------------------------------------------------------------------------------------------"


# --- Connect to Microsoft Graph ---

# Ensure you are connected with the necessary permissions (Group.ReadWrite.All)

try {

    # Removed -Force parameter from Connect-Mggraph

    Connect-Mggraph -Scopes "Group.ReadWrite.All" -TenantId $tenantId 

    Write-Host "Successfully connected to Microsoft Graph."

} catch {

    Write-Error "Failed to connect to Microsoft Graph. Ensure you have run 'Install-Module Microsoft.Graph' and have the correct permissions. Error: $($_.Exception.Message)"

    exit 1

}


# --- Get and Delete Groups ---

try {

    $groupsToDelete = Get-MgGroup -Filter "startswith(DisplayName, '$baseGroupDisplayNamePrefix')" -All

    

    if ($groupsToDelete.Count -eq 0) {

        Write-Host "No groups found with DisplayName starting with '$baseGroupDisplayNamePrefix'. Nothing to delete."

    } else {

        Write-Host "Found $($groupsToDelete.Count) groups to delete."

        foreach ($group in $groupsToDelete) {

            Write-Host "Deleting group: $($group.DisplayName) (ID: $($group.Id))"

            Remove-MgGroup -GroupId $group.Id -Confirm:$false # -Confirm:$false suppresses the prompt for each deletion

        }

        Write-Host "Finished attempting to delete all matching groups."

    }

} catch {

    Write-Error "An error occurred while getting or deleting groups: $($_.Exception.Message)"

} finally {

    # --- Disconnect from Microsoft Graph ---

    try {

        Disconnect-MgGraph

        Write-Host "Disconnected from Microsoft Graph."

    } catch {

        Write-Warning "Failed to disconnect from Microsoft Graph. You may need to close the PowerShell session manually."

    }

}


Write-Host "-----------------------------------------------------------------------------------------------------"

Write-Host "Cleanup script complete. Please verify in Microsoft 365 Admin Center that groups are gone."

Comments

Popular posts from this blog

Group deletion

Chart.JS does works if parent is hidden(), and CPU issue