Disable clutter Office 365 primary domain

How to get all Groups with Members in Office 365 PowerShell

This post is Part 3/3 of Office 365 groups VS Exchange Online groups.


Office 365 MsolGroups.

You need the Msol module for Office 365 in PowerShell.
You can find it here.

After you have installed the module you can log in to Office 365 with the following command.

Connect-MsolService

Now we can retrieve all Office 365 groups with this command.

Get-MsolGroup -all

-All Indicates that this cmdlet returns all results that it finds
For more about Get-MsolGroup click here.

With Get-MsolGroupMember you can get the members of a group.

Let’s say you have a group named Group5 you’ll need to use the command like this.

$Group = Get-Msolgroup -All | Where-Object {$_.DisplayName -eq "Group5"}
Get-MsolGroupMember -GroupObjectId $Group.ObjectId

So now we do this for one group. You can also do this for all groups in Office 365. Take a look at Paragraph O365 Full Script.

Here I retrieve all Office 365 groups in an array and then I read the members for each group. I then add it to a new PSObject and add it to $DataMSOL per member.

Now you could export in $DataMSOL to a CSV or text file.

You can use this for CSV. For more about Export-CSV click here.

$DataMSOL | Export-CSV -Path C:\temp\MSOLgroups.csv -NoTypeInformaton

And this for text files. For more about Out-File click here.

$DataMSOL | Out-File -FilePath C:\temp\MSOLGroups.txt

Suppose you only want the members of a certain set of groups you can use Where-Object with Get-MsolGroup. For more about Where-Object click here.

As an example I get all the groups that are Security Groups in Office 365.

Get-MsolGroup -All | Where-Object {$_.GroupType -eq "Security"}

O365 Full Script

$MSOLGPS = Get-MsolGroup -all
$DataMSOL = @()

Foreach ($MSOLGP in $MSOLGPS)
{
    Foreach ($Member in (Get-MsolGroupMember -GroupObjectId $MSOLGP.ObjectId))
    {
        $DataObject = New-Object PSObject  
        $DataObject | Add-Member -NotePropertyName "Member" -NotePropertyValue $Member.PrimarySmtpAddress
        $DataObject | Add-Member -NotePropertyName "MSOLGroup" -NotePropertyValue $MSOLGP.PrimarySmtpAddress
        $DataMSOL += $DataObject
    }
}

Any questions?

Do you want to know more or do you have any questions about the Office 365 part? Then leave a comment.


A little extra

This post contains PowerShell. Would you like to learn the basics better? I have created a new website to learn basic PowerShell in an ’emulator’ environment.
Click here to go learn Basic PowerShell.

Published by

Bas Wijdenes

My name is Bas Wijdenes and I work as a PowerShell DevOps Engineer. In my spare time I write about interesting stuff that I encounter during my work.

Leave a Reply

Your email address will not be published. Required fields are marked *