Automate exporting users licenses

Copper Contributor

Hi everyone,

 

Does anyone know how to automate exporting users with their license information and set it to be emailed to an admin each month? Using MFA enabled accounts so it looks like impossible to schedule this task with PowerShell script. Would be nice to find a guide if it's doable.

 

Thanks

3 Replies
you can use the below PowerShell script to export all users' licenses information and send them by email. to automate it you can create a scheduled task to run the script on monthly basis.

# Connect to Office 365
Connect-MsolService

# Get all users and their license information
$users = Get-MsolUser -All | Select-Object DisplayName, UserPrincipalName, LicenseAssignment

# Export the data to a CSV file
$users | Export-Csv -Path "C:\Users\yourusername\Documents\UserLicenses.csv" -NoTypeInformation

# Send an email with the CSV file as an attachment
$smtpServer = "smtp.office365.com"
$smtpPort = 587
$smtpUser = "email address removed for privacy reasons"
$smtpPassword = "yourpassword"
$emailFrom = "email address removed for privacy reasons"
$emailTo = "email address removed for privacy reasons"
$emailSubject = "Monthly User License Report"
$emailBody = "Please find attached the monthly report of user license information."

$emailAttachment = "C:\Users\yourusername\Documents\UserLicenses.csv"

$mailMessage = @{
To = $emailTo
From = $emailFrom
Subject = $emailSubject
Body = $emailBody
SmtpServer = $smtpServer
Port = $smtpPort
Credential = New-Object System.Management.Automation.PSCredential ($smtpUser, (ConvertTo-SecureString $smtpPassword -AsPlainText -Force))
Attachments = $emailAttachment
}

Send-MailMessage @mailMessage


Please click Mark as Best Response & Like if my post helped you to solve your issue. This will help others to find the correct solution easily.

@eliekarkafy 

 

Hi,

 

Thank you for your time and reply but unfortunately this won't work because I am using MFA and this script will ask for logon credentials and MFA code like the one I already have. I am after something more advanced so it will automate the logon process and MFA. Can something like this be done with Azure Automation? 

 

Thanks

@comptech8534 yes you can create a PowerShell runbook in azure automation and schedule the script to run based on your schedule. you can find the steps required in the below link. 

 

Tutorial - Create a PowerShell Workflow runbook in Azure Automation | Microsoft Learn

 

Please click Mark as Best Response & Like if my post helped you to solve your issue. This will help others to find the correct solution easily.