Public/Get-RDLicenseCount.ps1

<#
.SYNOPSIS
    Retrieves Remote Desktop Services (RDS) license count information for active users.
 
.DESCRIPTION
    This function retrieves information about users with active Remote Desktop Services (RDS) licenses in a specified search base within a domain.
 
.PARAMETER SearchBase
    Specifies the search base for the Active Directory query.
 
.PARAMETER DomainName
    Specifies the domain name for the Active Directory query.
 
.PARAMETER ExportToCSV
    Switch parameter to export the result to a CSV file named RDLicenseCount.csv.
 
.EXAMPLE
    # Retrieve RD license count information for active users in the specified search base within the domain.
    Get-RDLicenseCount -SearchBase "OU=Users,DC=example,DC=com" -DomainName "example.com"
 
.EXAMPLE
    # Retrieve RD license count information for active users and export the result to a CSV file.
    $domainDetails = @{
        Americas = "DC=AMERICAS, DC=test, DC=LOCAL"
        Asia = "DC=Asia, DC=test, DC=LOCAL"
        Europe = "DC=EUROPE, DC=test, DC=LOCAL"
    }
 
    # Loop through each domain, call the function, and export to CSV
    foreach ($domain in $domainDetails.Keys) {
        $results = Get-RDLicenseCount -SearchBase $domainDetails[$domain] -DomainName $domain.ToLower() -ExportToCSV
        $domainCount = $results.count
        $totalCount += $domainCount
    }
 
.NOTES
    Requires Active Directory module for PowerShell and appropriate permissions to query AD objects.
#>


function Get-RDLicenseCount {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true, Position = 0)]
        [ValidateNotNull()]
        [ValidateNotNullOrEmpty()]
        [string]$SearchBase,

        [Parameter(Mandatory = $true, Position = 1)]
        [ValidateNotNull()]
        [ValidateNotNullOrEmpty()]
        [string]$DomainName,

        [Parameter()]
        [switch]$ExportToCSV
    )

    # Retrieve AD users with Remote Desktop Services (RDS) licenses
    $users = Get-ADUser -Filter {Enabled -eq $true} -SearchBase $SearchBase -SearchScope Subtree -Server (Get-ADDomainController -Discover -DomainName $DomainName -Service adws | Select-Object -ExpandProperty Name) -Properties Enabled, msTSManagingLS, msTSExpireDate |
             Where-Object { $_.msTSExpireDate -gt (Get-Date) } |
             Select-Object SamAccountName, msTSManagingLS, msTSExpireDate

    # Output the result
    if ($ExportToCSV) {
        # Export to CSV file
        $users | Export-Csv -Path "C:\temp\$DomainName.csv" -NoTypeInformation
        Write-Host "RD license count information exported to C:\temp\$DomainName.csv"
    }
    else {
        # Output to console
        $users
    }
}