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
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.
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.
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.
# 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.
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
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
Not a reader? Watch this related video tutorial: