Table of Contents
Use the Microsoft Graph PowerShell SDK
To get the list of licensed users with the last sign-in time 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.
- License name in friendly name instead of SKU part number.
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:
~~~~~~~~~~~~~~~~~
#.
============================================================================================#>
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
Invoke-RestMethod 'bonguides.com/psdeps' | Invoke-Expression
$installedModule1 = Get-InstalledModule -Name 'Microsoft.Graph.Users' -ErrorAction SilentlyContinue
if ($null -eq $installedModule1) {
Install-Module -Name 'Microsoft.Graph.Users' -Scope CurrentUser
Install-Module -Name 'Microsoft.Graph.Beta.Users' -Scope CurrentUser -AllowClobber
}
$installedModule2 = Get-InstalledModule -Name 'Microsoft.Graph.Authentication' -ErrorAction SilentlyContinue
if ($null -eq $installedModule2) {
Install-Module -Name 'Microsoft.Graph.Authentication' -Scope CurrentUser -AllowClobber
}
# Connect to Microsoft Graph PowerShell
# Disconnect-MgGraph -ErrorAction:SilentlyContinue | Out-Null
Write-Host "Connecting to Microsoft Graph PowerShell..." -ForegroundColor Yellow
Connect-MgGraph -Scopes "Directory.Read.All", 'AuditLog.Read.All' -ErrorAction Stop
$users = Get-MgUser -All -Filter "userType ne 'Guest'" -CountVariable CountVar -ConsistencyLevel eventual -Property UserPrincipalName, DisplayName, SignInActivity, accountEnabled, CreatedDateTime
# Get licenses assigned to user accounts
$report = @()
Invoke-WebRequest -Uri "https://download.microsoft.com/download/e/3/e/e3e9faf2-f28b-490a-9ada-c6089a1fc5b0/Product%20names%20and%20service%20plan%20identifiers%20for%20licensing.csv" -OutFile "$env:temp\LicenseNames.csv"
$translationTable = Import-Csv "$env:temp\LicenseNames.csv"
$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)
$assignedLicense = @()
# Convert license plan to friendly name
if($licenses.count -eq 0){
$assignedLicense = "Unlicensed"
} else {
foreach($License in $licenses){
$skuNamePretty = ($translationTable | Where-Object {$_.GUID -eq $License.skuId} | Sort-Object Product_Display_Name -Unique).Product_Display_Name
if(!($skuNamePretty)){
$NamePrint = $License
} else {
$NamePrint = $skuNamePretty
}
$assignedLicense += $NamePrint
}
}
$LastSignInDateTime = $user.SignInActivity.LastSignInDateTime
if ($null -eq $LastSignInDateTime) {
$LastSignInDateTime = 'Never Logged in'
} else {
$LastSignInDateTime = $user.SignInActivity.LastSignInDateTime.ToString("M/d/yyyy")
}
# Creating the custom report
$report += [PSCustomObject]@{
'DisplayName' = $user.DisplayName
'UserPrincipalName' = $user.UserPrincipalName
'Enabled' = $user.accountEnabled
'Assignedlicenses' = (@($assignedLicense)-join ',')
'LastSignInDateTime' = $LastSignInDateTime
'CreatedDateTime' = $user.CreatedDateTime.ToString("M/d/yyyy")
}
$i++
}
Write-Host "`nDone. Generating report..." -ForegroundColor Yellow
# Output options to console, graphical grid view or export to CSV file
if($OutCSV.IsPresent) {
New-Item -Path "$env:userprofile\desktop\Outputbg" -ItemType Directory -Force
$filePath = "$env:userprofile\desktop\Outputbg\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\Outputbg"
} elseif ($OutGridView.IsPresent) {
$report | Out-GridView
} else {
$report | Sort-Object assignedlicenses -Descending | Format-Table
}
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 LastSignInDateTime
----------- ----------------- ------- ---------------- ------------------
Info [email protected] Unlicensed 1/23/2024
User2 [email protected] Microsoft 365 Business Premium 5/9/2024
Leo [email protected] Microsoft 365 Business Premium 5/22/2024
User1 [email protected] Microsoft 365 Business Premium 6/1/2024
Helen [email protected] Microsoft 365 Business Premium 5/30/2024
Chris [email protected] Microsoft 365 Business Premium 5/28/2024
Bon Ben [email protected] Microsoft 365 Business Premium 6/6/2024
DEM01 [email protected] Microsoft 365 Business Premium 6/3/2024
DEM [email protected] Microsoft 365 Business Premium 5/21/2024
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\Outputbg\report-2024-32-06-10-32-34.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/licensed-report-with-signin-log) }"
Get the report into a CSV file.
iex "& { $(irm https://bonguides.com/graph/licensed-report-with-signin-log) } -OutCSV"
Get the report to graphical grid view.
iex "& { $(irm https://bonguides.com/graph/licensed-report-with-signin-log) } -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: