Get-Wasted365License.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
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

}