Public/License.ps1
|
<# .SYNOPSIS Manages underutilized licenses. .DESCRIPTION This function finds users with a specific license who have not signed in for a certain number of days and provides options to remove or reassign the license. .PARAMETER SkuId The SKU ID of the license to check. .PARAMETER Days The number of days to check for stale sign-ins. .PARAMETER RemoveLicense If specified, the underutilized licenses will be removed. .PARAMETER ReassignLicenseTo The UPN or Id of a user to reassign the license to. .EXAMPLE Manage-O365UnderutilizedLicense -SkuId '6fd2c87f-b296-42f0-b197-1e91e994b900' -Days 60 -RemoveLicense .NOTES You must be connected to the Microsoft Graph with the 'User.ReadWrite.All' and 'Directory.Read.All' scopes before running this function. #> function Manage-O365UnderutilizedLicense { [CmdletBinding()] param( [Parameter(Mandatory=$true)] [string]$SkuId, [int]$Days = 30, [switch]$RemoveLicense, [string]$ReassignLicenseTo ) $UnderutilizedUsers = Get-O365UnderutilizedLicense -SkuId $SkuId -Days $Days if ($UnderutilizedUsers.Count -eq 0) { Write-Verbose "No underutilized licenses found for SkuId $SkuId." return } Write-Verbose "Found $($UnderutilizedUsers.Count) underutilized licenses." if ($RemoveLicense) { foreach ($User in $UnderutilizedUsers) { Write-Verbose "Removing license from $($User.UserPrincipalName)..." Set-MgUserLicense -UserId $User.Id -RemoveLicenses @($SkuId) -AddLicenses @{} } } elseif ($ReassignLicenseTo) { $ReassignUser = Get-MgUser -UserId $ReassignLicenseTo if (-not $ReassignUser) { Write-Warning "User not found: $ReassignLicenseTo" return } foreach ($User in $UnderutilizedUsers) { Write-Verbose "Reassigning license from $($User.UserPrincipalName) to $($ReassignUser.UserPrincipalName)..." Set-MgUserLicense -UserId $User.Id -RemoveLicenses @($SkuId) -AddLicenses @{} Set-MgUserLicense -UserId $ReassignUser.Id -AddLicenses @{SkuId = $SkuId} -RemoveLicenses @() } } return $UnderutilizedUsers } |