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

Export Office365 User Roles to CSV


$User = “user@tenant.onmicrosoft.com”
#$User = Read-host “Please enter Office365 Admin User name username@domain.onmicrosoft.com. “
$Creds = Get-Credential

#Connect-SPOService -Url https://tenant-admin.sharepoint.com -Credential $Creds
Connect-MsolService -Credential $Creds

$AllUserRoles = @()

$Users = Get-MsolUser -All
foreach($user in $Users)
{
    $UserRoles = Get-MsolUserRole -UserPrincipalName $User.UserPrincipalName
    foreach($role in $UserRoles)
    {
        $aRole = New-Object PSObject
        $UserName = $User.UserPrincipalName
        $RoleName = $role.Name.ToString()

        Add-Member -input $aRole noteproperty ‘UserName’ $UserName
        Add-Member -input $aRole noteproperty ‘RoleName’ $RoleName
        $AllUserRoles += $aRole
    }
}

$AllUserRoles | export-csv -Path C:\Scripts\SPOUserRoles.csv -NoTypeInformation -Force