Export Office 365 User Roles and Members to Text or CSV file

$Creds = Get-Credential -Message “Please enter SharePoint Online Administrator User and password.”
Connect-MsolService -Credential $Creds

$Roles = Get-MsolRole | ? Name -Like “*”
foreach($Role in $Roles)
{
    $RoleName = $Role.Name
    $Members = Get-MsolRoleMember -RoleObjectId $Role.ObjectId
    if($Members)
    {
        $Role.Name | Out-File -FilePath C:\Scripts\Admins.txt -Append -Encoding default -Force
        $Members | Out-File -FilePath C:\Scripts\Admins.txt -Append -Encoding default -Force
    }
    else
    {
        $Role.Name | Out-File -FilePath C:\Scripts\Admins.txt -Append -Encoding default -Force
        “No Members” | Out-File -FilePath C:\Scripts\Admins.txt -Append -Encoding default -Force
    }

}

# You can also create a better CSV

$UserRoles = @()
$Roles = Get-MsolRole | ? Name -Like “*”
foreach($Role in $Roles)
{
    $RoleName = $Role.Name
    $Members = Get-MsolRoleMember -RoleObjectId $Role.ObjectId
    if($Members)
    {
        foreach($Member in $Members)
        {
            $Role = New-Object PSObject
            Add-Member -input $Role noteproperty ‘RoleName’ $RoleName
            Add-Member -input $Role noteproperty ‘RoleMemberType’ $Member.RoleMemberType
            Add-Member -input $Role noteproperty ‘EmailAddress’ $Member.EmailAddress
            Add-Member -input $Role noteproperty ‘DisplayName’ $Member.DisplayName
            Add-Member -input $Role noteproperty ‘isLicensed’ $Member.isLicensed
            $UserRoles += $Role
        }
    }
    else
    {
        $Role = New-Object PSObject
        Add-Member -input $Role noteproperty ‘RoleName’ $RoleName
        Add-Member -input $Role noteproperty ‘RoleMemberType’ “”
        Add-Member -input $Role noteproperty ‘EmailAddress’ “”
        Add-Member -input $Role noteproperty ‘DisplayName’ “”
        Add-Member -input $Role noteproperty ‘isLicensed’ “”
        $UserRoles += $Role
    }
}
$UserRoles | Out-GridView

Advertisements

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 )

Twitter picture

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

Facebook photo

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

Google+ photo

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

Connecting to %s