Powershell Find Users Missing a License in Office 365

Issue:

I needed to find accounts that were missing a second license in Office 365.  The example below will help you find users missing a secondary license.

Solution:

#Review Student Missing Licensing


$username = "tenantadmin@domain.com";
$logfile = 'c:\temp\UsersMissingLicense.txt';

$logFileStream = [System.IO.StreamWriter] $logfile

try
{
    $mycreds = Get-Credential -Message "Office 365 Credential" -UserName $username

    Connect-MsolService -credential $mycreds;

    $licenseduserList = Get-MsolUser -All | where { $_.isLicensed -eq "True" -and ($_.UserPrincipalName -like '8*' -or  $_.UserPrincipalName -like '9*')} | Sort-Object UserPrincipalName
    #$licenseduserList = Get-MsolUser -All -Synchronized | where { $_.isLicensed -eq "True" } | Sort-Object UserPrincipalName
    #Get-MsolAccountSku | Format-Table -AutoSize > 'c:\temp\Licenses.txt'
    ForEach ($muser in $licenseduserList)
    {
        $haslic = 0;
        $lics = $muser.Licenses
        foreach ($lic in $lics)
        {
        
            if ($($lic.AccountSkuId) -eq '[ORGANIZATION SITE]:[LICENSE NAME]')
            {
                $haslic = 1;
            }

        }
        if ($haslic -eq 0)
        {
            WRITE-HOST "$($muser.UserPrincipalName)"
            $streamExportFile.WriteLine($($muser.UserPrincipalName))
        }
    }
}
catch
{
    $ErrorMessage = $_.Exception.Message
    $FailedItem = $_.Exception.ItemName
    WRITE-HOST "FailedItem:  $FailedItem"
    WRITE-HOST "Error:  $ErrorMessage"
}
finally
{
    $streamExportFile.Close()
}

 

Resources:

http://www.questiondriven.com/2016/09/12/office-365-powershell-examples/

Leave a Reply

%d bloggers like this: