Get-Wasted365License.ps1

function Get-Wasted365License
{
  <#
      .SYNOPSIS
      Checks EOL for users with associated licenses who are also disabled in AD
      .DESCRIPTION
      This script is meant to find disabled users in Active Directory who are burning a 365 license.
      .EXAMPLE
      Get-Wasted365License -ProductType EnterprisePack -LicensePrefix SPANG1
      Gets all users who are disabled that have an associated SPANG1:ENTERPRISEPACK license
  #>


  [CmdletBinding()]
  param
  (
    # IFS Instance Selection
    [Parameter(ParameterSetName = 'ParameterSet1', Mandatory = $true, HelpMessage = 'Select the 365 License Type')]
    [ValidateSet('EnterprisePack','Visio','Project')]
    [string]
    $ProductType,
    [Parameter(Mandatory = $True)]
    [string]
    $LicensePrefix
  )

    if ((Get-ExchangeOnlineConnectionState) -eq 'Disconnected') {
      $Cred = Get-Credential -Message "Enter your username and password for connecting to Exchange & Azure."
    Connect-ExchangeOnline -Credential $Cred; Connect-MsolService -Credential $Cred}

    switch ($ProductType) 
    {
      EnterprisePack 
      {
        $SKU = 'ENTERPRISEPACK'
      }
      Visio 
      {
        $SKU = 'VISIOCLIENT'
      }
      Project 
      {
        $SKU = 'PROJECTCLIENT'
      }
    }

    $ProductCompleteSKU = "$($LicensePrefix):$($SKU)"

    $MSOLUsers = Get-MsolUser -All
    $LicensedUsers = $MSOLUsers | Where-Object -FilterScript {
      $_.Licenses.AccountSKUId -eq $ProductCompleteSKU
    }

    $wastedLicense = @()
    foreach ($user in $LicensedUsers) 
    {
      $name = ($user.UserPrincipalName.Split('@')[0])
      if ((Get-ADUser -Identity $name -ErrorAction SilentlyContinue).Enabled -eq $false) 
      {
        $wastedLicense += $name 
      }
    }

    Remove-Variable -Name ProductType, SKU, LicensedUsers, user, name, ProductCompleteSKU

    return $wastedLicense
  
Write-host "You must be connected to Exchange Online and MSOLService." -ForegroundColor Green -BackgroundColor Black
Write-host "Use Connect-ExchangeOnline & Connect-MSOLService to ensure you are connected as required." -ForegroundColor Green -BackgroundColor Black

}