πŸ”§ New: User Management Graph PowerShell Toolkit

Simplify user tasks like bulk creation, updates, password resets, deletions, license checks & more β€” all from one place.

πŸš€ Launch Toolkit

Fetch and Email Recently Created Microsoft 365 Groups

Keeping track of newly created Microsoft 365 groups is crucial for governance and security. Groups can be created through Teams, Outlook, SharePoint, or other integrated services, making it easy to lose visibility into new additions. This script helps administrators stay informed by automatically fetching all Microsoft 365 groups created in the last 30 days, exporting their details, and emailing the report to the administrator.


i) The Script


    # ============================
    # Config
    # ============================
    # Admin mailbox to receive the report
    $AdminUPN = "samadmin@7xh7fj.onmicrosoft.com"   # replace
    # Lookback window (days)
    $LookbackDays=30
    #= = = = = = = = = = = = = = = = = = = = = = = = = = = =# 1) Compute start date (UTC) and fetch recent M365 groups
    $StartUtc =(Get-Date).ToUniversalTime().AddDays(-$LookbackDays).ToString("o") # ISO 8601, e.g., 2025-09-10T12:34:56.0000000Z
    # Retrieve groups created since the cutoff.
    # Use ConsistencyLevel 'eventual' for reliability with server-side filtering.
    $RecentGroups=Get-MgGroup -All `
    -Filter "createdDateTime ge $StartUtc" `
    -ConsistencyLevel eventual `
    -CountVariable Records `
    -Property Id, DisplayName, GroupTypes, MailEnabled, SecurityEnabled, Visibility, MailNickname, CreatedDateTime, ResourceProvisioningOptions
    #= = = = = = = = = = = = = = = = = = = = = = = = = = = =# 2) Shape data for export
    $ReportRows =$RecentGroups | Select-Object `
    @{n='GroupDisplayName' ; e={$_.DisplayName}},
    @{n='GroupId' ; e={$_.Id}},
    @{n='GroupType' ; e={
    if ($_.GroupTypes -contains 'Unified' ) { 'Microsoft 365 Group' }
    elseif ($_.SecurityEnabled) { 'Security Group' }
    elseif ($_.MailEnabled) { 'Distribution Group' }
    else { 'Other' }
    }},
    MailEnabled,
    SecurityEnabled,
    Visibility,
    MailNickname,
    @{n='HasTeam' ; e={ ($_.ResourceProvisioningOptions -contains 'Team' ) }},
    @{n='CreatedDateTime(UTC)' ; e={[datetime]$_.CreatedDateTime}}
    #= = = = = = = = = = = = = = = = = = = = = = = = = = = =# 3) Export to CSV
    $ReportPath ="$env:TEMP\RecentlyCreatedGroups_${LookbackDays}d.csv"
    $ReportRows |
    Sort-Object 'CreatedDateTime(UTC)' |
    Export-Csv -Path $ReportPath -NoTypeInformation -Encoding UTF8
    #= = = = = = = = = = = = = = = = = = = = = = = = = = = =# 4) Email the report to the administrator
    $groupCount =@($ReportRows).Count
    $Subject="Recently Created M365 Groups (last $LookbackDays days) β€” $(Get-Date -Format 'yyyy-MM-dd')"
    $Body=@"
           Hello Admin,
Attached is the report of Microsoft 365 groups created in the last $LookbackDays days
Total new groups: $groupCount.
Fields: GroupDisplayName, GroupId, GroupType, MailEnabled, SecurityEnabled, Visibility, MailNickname, HasTeam, CreatedDateTime (UTC).
Regards,
Graph PowerShell Script
"@

# Read and attach the CSV
$AttachmentContent = [System.Convert]::ToBase64String([System.IO.File]::ReadAllBytes($ReportPath))
$Attachments = @(
    @{
        "@odata.type" = "#microsoft.graph.fileAttachment"
        Name          = [System.IO.Path]::GetFileName($ReportPath)
        ContentBytes  = $AttachmentContent
    }
)

# Build the message payload
$Message = @{
    Message = @{
        Subject = $Subject
        Body    = @{
            ContentType = "HTML"
            Content     = $Body
        }
        ToRecipients = @(
            @{ EmailAddress = @{ Address = $AdminUPN } }
        )
        Attachments = $Attachments
    }
    SaveToSentItems = "true"
}

# Send the email from admin's mailbox
Send-MgUserMail -UserId $AdminUPN -BodyParameter $Message

Write-Host "Recently-created Microsoft 365 groups report (last $LookbackDays days) emailed successfully to $AdminUPN"



ii) How the Script Works

  1. Configuration – The $AdminUPN variable sets the email address where the report will be delivered. The $LookbackDays variable determines the time window (default: 30 days).
  2. Graph Connection – The script connects to Microsoft Graph using the required scopes:
    • Group.Read.All - To read Microsoft 365 group details.
    • Directory.Read.All – To retrieve extended directory information.
    • Mail.Send – To send the report via email.
  3. Fetch Groups – The script uses Get-MgGroup to retrieve groups where createdDateTime is greater than the calculated start date.
  4. Format Data Each group’s display name, ID, type, visibility, and creation time are formatted, along with an indicator (HasTeam) showing whether the group is linked to a Microsoft Teams team.
  5. Export Report – The script exports the report as a CSV file stored in the system’s temporary folder.
  6. Email Report – The CSV is attached to an email and sent to the administrator, summarizing the total new groups created during the period.

iii) Further Enhancements

  • Change the Reporting Window – Modify $LookbackDays to 7, 14, or 60 as needed
  • Add Group Owners – Extend the report to include group owners using Get-MgGroupOwner.
  • Include Member Count – Add the number of members per group for management insights.
  • Scheduled Automation – Schedule the script with Windows Task Scheduler or Azure Automation for regular monitoring.
  • Alert Threshold – Configure it to send alerts if the number of new groups exceeds a certain threshold (useful for auditing).

iv) Possible Errors & Solutions

Error Cause Solution
Insufficient privileges to complete the operation Missing Microsoft Graph permissions. Ensure you connect using Group.Read.All, Directory.Read.All, and Mail.Send.
Send-MgUserMail : Resource not found The $AdminUPN specified is not a valid mailbox. Replace $AdminUPN with a valid mailbox-enabled account.
BadRequest when filtering on createdDateTime Incorrect date format in $StartUtc. Always format the date as ISO 8601 using .ToString("o").
Empty CSV File No groups created in the last 30 days. This is expected; the report still generates an empty file for consistency.

v) Conclusion

This Microsoft Graph PowerShell script helps administrators maintain visibility into newly created Microsoft 365 groups, ensuring proactive governance and security awareness. By automatically emailing the report, it saves time, eliminates manual checks, and provides instant insight into new group creations.

With further enhancements like including owners, member counts, or alert thresholds, this script can become a key component in your Microsoft 365 governance and compliance toolkit.


Graph PowerShell Explorer Widget

20 Graph PowerShell cmdlets with easily accessible "working" examples.


Permission Required

Example:


                


                


                

© m365corner.com. All Rights Reserved. Design by HTML Codex