GitHub Icon Image

Delete all Microsoft 365 groups

Summary

There are so many different ways to create Microsoft 365 groups. Teams, Planner, SharePoint team sites, etc. — you can accumulate a lot of them very fast. Use this script below to delete the ones you no longer need.

Warning

Please be aware this script contains a command that will remove or delete an artifact, ensure you test and understand the implications of running the script.

  • CLI for Microsoft 365 with PowerShell
  • Microsoft 365 CLI with Bash
$sparksjoy = "All Company", "TEMPLATE Project", "We have cats in this team! Join!"
$groups = m365 aad o365group list -o json | ConvertFrom-Json
$groups = $groups | where {-not ($sparksjoy -contains $_.displayName)}
if ($groups.Count -eq 0) { break }
$groups | Format-Table displayName
Write-Host "Total:" $groups.Count
Read-Host -Prompt "Press Enter to start deleting (CTRL + C to exit)"
$progress = 0
$total = $groups.Count
foreach ($group in $groups)
{
    $progress++
    Write-Host $progress / $total":" $group.displayName
    m365 aad o365group remove --id $group.id --confirm
}

Check out the CLI for Microsoft 365 to learn more at: https://aka.ms/cli-m365

#!/bin/bash

# requires jq: https://stedolan.github.io/jq/

sparksjoy=("All Company" "TEMPLATE Project" "We have cats in this team! Join!")
groupstoremove=()
while read o365group; do
  exists=false
  displayName=$(echo $o365group | cut -d';' -f 1)
  for keep in "${sparksjoy[@]}"; do
    if [ "$keep" == "$displayName" ] ; then
      exists=true
      break
    fi
  done
  if [ "$exists" = false ]; then
    groupstoremove+=("$o365group")
  fi
done < <(m365 aad o365group list -o json | jq -r '.[] | .displayName + ";" + .id')

if [ ${#groupstoremove[@]} = 0 ]; then
  exit 1
fi

printf '%s\n' "${groupstoremove[@]}"
echo "Press Enter to start deleting (CTRL + C to exit)"
read foo

for o365group in "${groupstoremove[@]}"; do
  displayName=$(echo $o365group | cut -d';' -f 1)
  id=$(echo $o365group | cut -d';' -f 2)
  echo "Deleting $displayName..."
  m365 aad o365group remove --id "$id" --confirm
done

Check out the CLI for Microsoft 365 to learn more at: https://aka.ms/cli-m365

Source Credit

Sample first appeared on Delete all Microsoft 365 groups | CLI for Microsoft 365

Contributors

Author(s)
Laura Kokkarinen

Disclaimer

THESE SAMPLES ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.

Back to top Script Samples
Generated by DocFX with Material UI