Powershell script to get all user licenses based on department. Will use in a Power Automate to send in an email
Run this command which will prompt you to enter username and password
    $credential = Get-Credential
Test that it works by running this command which should not prompt for password if working
    Connect-MsolService -Credential $credential
Create the following variables
    $credential.Password | ConvertFrom-SecureString | Out-File C:\Temp\mypass.txt
    $AdminName = “myname@mydomain.com”
    $Pass = Get-Content “C:\Temp\mypass.txt” | ConvertTo-SecureString
    $Credential = new-object -typename System.Management.Automation.PSCredential -argumentlist $AdminName, $Pass
Test login again on a new PowerShell terminal. You should not be prompted to login
    Connect-MsolService -Credential $Credential
    Get-MsolUser | Where-Object { $_.isLicensed -eq "True"} | Where {$_.Department -eq "DepartmentName"} | Select-Object DisplayName, Department | Sort-Object DisplayName| Export-Csv "C:\Temp\Licenses.csv"
Capture Disabled user accounts that still have licenses assigned
    $AdminName= "myemail@mydomain.com"
    $Password = Get-Content "C:\Temp\mypass.txt" | ConvertTo-SecureString
    $Credential = new-object -TypeName System.Management.Automation.PSCredential -ArgumentList $AdminName, $Password
    Connect-MsolService -Credential $Credential
    Get-MsolUser -EnabledFilter DisabledOnly -ALL | Where-Object { $_.isLicensed -eq "True"} | Sort-Object UserPrincipalName
Remove licenses from a list of users.
Create a list of users one name per line
    $AdminName= "myemail@mydomain.com"
    $Password = Get-Content "C:\Temp\mypass.txt" | ConvertTo-SecureString
    $Credential = new-object -TypeName System.Management.Automation.PSCredential -ArgumentList $AdminName, $Password
    Connect-MsolService -Credential $Credential
    ### create the variable based on the list of users
    $users=Get-Content C:\Temp\users.txt
    ### Run a loop based on the variable
    for ($i=0; $i -lt $users.Count; $i++)
    {
    Set-MsolUserLicense -UserPrincipalName $users[$i] -RemoveLicenses 'NAME_OF_LICENSE'
    }
To add a license change -RemoveLicenses to -AddLicenses
  
          Reading time: 2 minutes