Get Office 365 users licenses

Hey scripters, today I want to show you how in easy way get Office 365 users licenses.

Script which I’ve prepared connect to Office 365 tenant and in first step check all licenses.
Once it is done all users which have attribute isLicensed flagged as True are gathered.
In next steps script is filtering users base on license name and export those information to CSV files.

Note:
Remember to install MSOnline module before running script.

Script:

#Provide directory path and prefix for output files
$LogDirectory = "c:\Temp\"
$LogFileName = "Office_365_License_"

if(!(Test-Path $LogDirectory))
{
    Write-Host "Provided directory was not found, directory will be created now..."
    New-Item -Path $LogDirectory -ItemType Directory
}

Import-Module MSOnline
Connect-MsolService

Write-Host "Connecting to Office 365..."

# Get a list of all licences available for tenant and gahter users which have license assigned
$LicenseTypes = Get-MsolAccountSku | Where {$_.ConsumedUnits -ge 1}
$Users = Get-MsolUser -All| Where-Object {$_.isLicensed -eq "True"}

foreach ($license in $LicenseTypes) 
{	

    Write-Host "Gathering users with license " $LicenseName -ForegroundColor Green
	
	$AccountsArray = @()
    $LicenseName = $license.AccountSkuId
    $FileLicenseName = $license.accountskuid.Replace(':','')
    	
	# Gather accounts which have specific license assigned
	$Accounts = $Users | Where-Object {$_.licenses.accountskuid -contains $LicenseName}

	foreach ($Account in $Accounts) {
		
		$thislicense = $Account.licenses | Where-Object {$_.accountskuid -eq $LicenseName}
		$Properties =  @{
         "UserPrincipalName" = $Account.UserPrincipalName
         "DisplayName" = $Account.DisplayName
         "AccountSku" = $LicenseName
        }
		
        foreach ($row in $($thislicense.servicestatus)) {
			
            $Properties.Add($row.ServicePlan.ServiceName,$row.ProvisioningStatus)
		
		}
		
        $AccountArrayRow = New-Object PSObject -Property $Properties
        $AccountsArray += $AccountArrayRow
	}
    
    $FileName = ($LogDirectory+$LogFileName+$FileLicenseName)
    $AccountsArray | Export-CSV -Path $FileName'.csv' -NoTypeInformation
    
    Write-Host "Export to file for license $LicenseName completed" -ForegroundColor Green
}			

Write-Host ("Output files available under " + $LogDirectory) -ForegroundColor Green

In the result you will get Office 365 users licenses splitted into separate files.
It should looks simialr to below.

Script can be usefull in case that you want to remove licenses unnecessary assigned to some users.

I hope it will be usefull for some of you 😉
Enjoy!

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.