Governance : Scan Office 365 Groups created with User First or Last Name using Office 365 CLI Commands

We can use the group naming policy to enforce a consistent naming strategy for groups created by users in our organization. A naming policy can help us and our users identify the function of the group. We can use the policy to block specific words from being used in group names and aliases. But what if we need to find out the list of Office 365 groups created with user’s first or last name as their mail?

The answer is very simple. We can use few lines of Office 365 CLI commands for this usecase. This sample script scans the Office 365 groups that may contain user’s first or last name as the group mail.

Note: The filter condition can be changed as per your requirement.

$groupsToFlag = @()

$users = o365 aad user list --properties 'displayName,givenName,surname' -o json | ConvertFrom-Json
$groups = o365 aad o365group list  -o json | ConvertFrom-Json

foreach ($user in $users) {
    $userGivenName = $user.givenName
    $userSurname = $user.surname

    $groupsMatch = $groups | Where-Object { $_.mail -like "*$userGivenName*" -or $_.mail -like "*$userSurname*" }

    foreach ($group in $groupsMatch) {
        $groupObject = New-Object -TypeName PSObject
        $groupObject | Add-Member -MemberType NoteProperty -Name "groupId" -Value $group.id
        $groupObject | Add-Member -MemberType NoteProperty -Name "groupDisplayName" -Value $group.displayName
        $groupObject | Add-Member -MemberType NoteProperty -Name "groupMail" -Value $group.mail
        $groupObject | Add-Member -MemberType NoteProperty -Name "userGivenName" -Value $userGivenName
        $groupObject | Add-Member -MemberType NoteProperty -Name "userSurname" -Value $userSurname
        $groupsToFlag += $groupObject
    }
}

$groupsToFlag | Format-Table -AutoSize

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.