Learning and Sharing
  • Home
  • Blog
  • Linux
  • macOS
  • Virtualization
    • VMware
    • VirtualBox
  • Windows
    • Windows 11
    • Windows 10
    • Windows Server
  • Series
    • Symantec
    • Intune
    • Microsoft Azure
    • Powershell
    • VirtualBox
    • VMware
    • PowerShell Learning
    • Microsoft Graph
  • More
    • Auto Installation
    • AEC Installation
  • Contact
No Result
View All Result
  • Home
  • Blog
  • Linux
  • macOS
  • Virtualization
    • VMware
    • VirtualBox
  • Windows
    • Windows 11
    • Windows 10
    • Windows Server
  • Series
    • Symantec
    • Intune
    • Microsoft Azure
    • Powershell
    • VirtualBox
    • VMware
    • PowerShell Learning
    • Microsoft Graph
  • More
    • Auto Installation
    • AEC Installation
  • Contact
No Result
View All Result
No Result
View All Result

How to Export Users with License Assignments in Microsoft 365 Using Microsoft Graph

December 19, 2023
in Blog, Microsoft Graph, Powershell
0
ADVERTISEMENT

Table of Contents

Use the Microsoft Graph PowerShell SDK

To get the list of users with license assignments in Microsoft 365, you can use the Microsoft Graph PowerShell. We have created a PowerShell script to ease your work automatically.

Script Highlights:

  • Install the required Microsoft Graph PowerShell SDK modules upon your confirmation.
  • Install only the required modules (3 modules) instead of all Microsoft modules (~90 modules). This will help you speed up the process in the first run or run script on a new computer.
  • Output options direct to console, export to a CSV file or open in the graphical grid view.

Click on the below button to get the code snippet. Then create your own PowerShell script. 

<#=============================================================================================
Script by    : Leo Nguyen
Website      : www.bonguides.com
Telegram     : https://t.me/bonguides
Discord      : https://discord.gg/fUVjuqexJg
YouTube      : https://www.youtube.com/@BonGuides

Script Highlights:
~~~~~~~~~~~~~~~~~
#. Single script allows you to generate user report with license assigments and account status
============================================================================================#>

param (
    [switch]$OutCSV,
    [switch]$OutGridView
)

if (-not([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
    Write-Warning "You need to have Administrator rights to run this script!`nPlease re-run this script as an Administrator in an elevated powershell prompt!"
    break
}

# Install the required Microsoft Graph PowerShell SDK modules
    Set-ExecutionPolicy Bypass -Scope Process -Force | Out-Null
    iex "& { $(irm bonguides.com/graph/modulesinstall) } -InstallBasic"

# Connect to Microsoft Graph PowerShell
    $report = @()
    $uri = "https://bonguides.com/files/LicenseFriendlyName.txt"
    $friendlyNameHash = Invoke-RestMethod -Method GET -Uri $uri | ConvertFrom-StringData

    Disconnect-MgGraph -ErrorAction:SilentlyContinue | Out-Null

    Write-Host "Connecting to Microsoft Graph PowerShell..." -ForegroundColor Yellow
    Connect-MgGraph -Scopes "Directory.Read.All" -ErrorAction Stop
    $users  = Get-MgBetaUser -All

# Get licenses assigned to user accounts
    $i = 1
    foreach ($user in $users) {
        Write-Progress -PercentComplete ($i/$($users.Count)*100) -Status "Processing: $($user.UserPrincipalName) - $($user.DisplayName)" -Activity "Processing: ($i/$($users.Count))"
        $licenses = (Get-MgBetaUserLicenseDetail -UserId $user.id).SkuPartNumber
        $assignedLicense = @()
        
        # Convert license plan to friendly name
        if($licenses.count -eq 0){
            $assignedLicense = "Unlicensed"
        } else {
            foreach($License in $licenses){
                $EasyName = $friendlyNameHash[$License]
                if(!($EasyName)){
                    $NamePrint = $License
                } else {
                    $NamePrint = $EasyName
                }
                $assignedLicense += $NamePrint
            }
        }

        # Creating the custom report
        $report += [PSCustomObject]@{
            'DisplayName' = $user.DisplayName
            'UserPrincipalName' = $user.UserPrincipalName
            'Enabled' = $user.accountEnabled
            'Assignedlicenses'=(@($assignedLicense)-join ',')
        }
        $i++
    }

Write-Host "`nDone. Generating report..." -ForegroundColor Yellow

# Output options to console, graphical grid view or export to CSV file
if($OutCSV.IsPresent) {
    $filePath = "$env:userprofile\desktop\report-$(Get-Date -Format yyyy-mm-dd-hh-mm-ss).csv"
    $report | Export-CSV $filePath -NoTypeInformation -Encoding UTF8
    Write-Host "`nThe report is saved to: $filePath `n" -ForegroundColor Cyan
    Invoke-Item "$env:userprofile\desktop"
} elseif ($OutGridView.IsPresent) {
    $report | Out-GridView
} else {
    $report | Sort-Object assignedlicenses -Descending
}

Script Execution:

Windows PowerShell needs to be configured to run scripts, and by default, it isn’t. You need to configure this setting only once on your computer, not every time you connect. To do it, let right-click on the Windows start icon then open Windows PowerShell (Terminal) as administrator.

1️⃣ Run the below command to set the execution policy to RemoteSigned. This policy requires scripts downloaded from internet must be signed to be able to run and doesn’t require digital signatures on scripts that are written on the local computer and not downloaded from the internet.

Set-ExecutionPolicy RemoteSigned -Force
Note Related: How to Configure the PowerShell Execution Policy on Windows

2️⃣ Once the execution policy has been configured, we’ve created a PowerShell script. For example, our script is saved in D:\Scripts\report.ps1. Run the script as follows:

D:\Scripts\report.ps1

3️⃣ In the first run, the script will check then install the required Microsoft Graph PowerShell module if it has not been installed. Type then hit to install the required modules.

# Output
Important: Microsoft Graph module is unavailable.
It is mandatory to have this module installed in the system to run the script successfully.   
Are you sure you want to install Microsoft Graph module? [Y] Yes [N] No: Y      
              
Installing Microsoft Graph module...                                                        
Microsoft Graph module is installed in the machine successfully

4️⃣ Once the required modules have been installed. You need to connect to the Microsoft Graph PowerShell using an administrative account.

HbvFnACibw6JKX58mWppBAOkH1YoerH4G9wm2joqvHaS1Xh88LCCa8vQcPuS

5️⃣ In the first sign-in, you need to consent permissions to the app named Microsoft Graph Command Line Tools. Let’s select the checkbox Consents on behalf of your organization then click the Accept button.

qdjMrmArvsZChexcIMsiTBxROO5fmTLFf65gOf0qXIdooPr7aRXwakEWTyWD

If has no issue, you would get the Welcome to Microsoft Graph banner then script will run automatically. On the console, you can see the progress when the script is running. and the result would be shown in the PowerShell console directly.

y4L5ZTyjRMSYhEBKFhkfTEc5uIP3qNQDEsE8JJdb1ds9c045hP2XiPcljxGZ
# Output
...
Done. Generating report...

DisplayName       UserPrincipalName         Enabled Assignedlicenses
-----------       -----------------         ------- ----------------
Joni Sherman      [email protected]              True Unlicensed
Lee Gu            [email protected]               True Unlicensed
Allan Deyoung     [email protected]             True Microsoft Flow (Free)
Mallory Cortez    [email protected]           True Enterprise Mobility + Security E5,Windows E3
...

Output options

Export to CSV

The results from the script output can be show in graphical grid view or export to a CSV file. For example, execute the script with -OutCSV parameter will export the output to a CSV file.

D:\scripts\report.ps1 -OutCSV
# Output
Connecting to Microsoft Graph PowerShell...                                
Welcome to Microsoft Graph!
Connected via delegated access using 14d82eec-204b-4c2f-b7e8-296a70dab67e 
Readme: https://aka.ms/graph/sdk/powershell                               
SDK Docs: https://aka.ms/graph/sdk/powershell/docs
API Docs: https://aka.ms/graph/docs

NOTE: You can use the -NoWelcome parameter to suppress this message.
Done. Generating report...
The report is saved to: C:\Users\admin\desktop\report-2023-53-19-09-53-33.csv

By default, the CSV file would be saved on your Desktop.

Ts8AyKT866trhtpuXRkWGfSBYqjJWgdDPjdIjXISTfUrKeLqxAvZpAYH8PPq

Show in Gridview

For quick filter and don’t want to create a CSV file. Run the script with -OutGridView is the good option. The output shows in a new PowerShell window.

D:\scripts\report.ps1 -OutGridView
MWUyzbOda6XDafCEgDwbg74bbBK7cCI18Dc4OKkZZZ9g6ebwafRxYLF4Xpxh

Single line PowerShell script

Alternatively, we’ve created a PowerShell script on GitHub. All you need to do is simply run the single-line command below to get the report automatically.

Get the report to the console directly.

iex "& { $(irm https://bonguides.com/graph/user-report-license) }"

Get the report into a CSV file.

iex "& { $(irm https://bonguides.com/graph/user-report-license) } -OutCSV"

Get the report to graphical grid view.

iex "& { $(irm https://bonguides.com/graph/user-report-license) } -OutGridView"

Manage Microsoft 365 Using Microsoft Graph

You can also take a look at the following Microsoft Graph posts that help to manage Microsoft 365 efficiently.

  • Create a new user
  • Create bulk users in Microsoft 365
  • Get a list of all users in Microsoft 365
  • Update user properties
  • Add a user to a group
  • Add bulk users to a group
  • Remove users from a group
  • Remove multiple users from a group
  • Assign managers for Microsoft 365 users
  • Assign licenses to users
  • Removing licenses from user accounts
  • Delete a user from Microsoft 365
  • How to use Get-MgUser cmdlet
ADVERTISEMENT

Not a reader? Watch this related video tutorial:

5/5 - (1 vote)
Previous Post

How to Enable Outlook Modern Authentication from Registry Setting

Next Post

How to Export Users with Roles Assignment in Microsoft 365 using Microsoft Graph PowerShell

Related Posts

Running Hyper-V and VMware Workstation on The Same Machine

August 15, 2024

How to Uninstall All Autodesk Products At Once Silently

July 29, 2024
Ftr5

How to Uninstall the Autodesk Genuine Service on Windows

July 29, 2024
Ftr19

How to Fix Windows Cannot Read the ProductKey From the Unattend Answer File in VirtualBox

July 26, 2024
Ftr25

How to Update Windows Terminal in Windows 10/11

July 26, 2024

How to Disable The Beep Sound in WSL Terminal on Windows

July 26, 2024

Leave a Reply Cancel reply

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

Recent Posts

  • How To Turn On uBlock Origin Extension in Chrome (2025)
  • Images Hidden Due To Mature Content Settings In CivitAI
  • Azure OpenAI vs Azure AI Hub, How to Choose the Right One for Your Needs

Categories

Stay in Touch

Discord Server

Join the Discord server with the site members for all questions and discussions.

Telegram Community

Jump in Telegram server. Ask questions and discuss everything with the site members.

Youtube Channel

Watch more videos, learning and sharing with Leo ❤❤❤. Sharing to be better.

Newsletter

Join the movement and receive our weekly Tech related newsletter. It’s Free.

General

Microsoft Windows

Microsoft Office

VMware

VirtualBox

Technology

PowerShell

Microsoft 365

Microsoft Teams

Email Servers

Copyright 2025 © All rights Reserved. Design by Leo with ❤

No Result
View All Result
  • Home
  • Linux
  • Intune
  • macOS
  • VMware
  • VirtualBox
  • Powershell
  • Windows 10
  • Windows 11
  • Microsoft 365
  • Microsoft Azure
  • Microsoft Office
  • Active Directory

No Result
View All Result
  • Home
  • Linux
  • Intune
  • macOS
  • VMware
  • VirtualBox
  • Powershell
  • Windows 10
  • Windows 11
  • Microsoft 365
  • Microsoft Azure
  • Microsoft Office
  • Active Directory