Private/Send-CitrixLicenseReport.ps1

<#
.SYNOPSIS
    Sends an automated email with the Citrix license usage report.
 
.DESCRIPTION
    The `Send-CitrixLicenseReport` function retrieves the latest Citrix license usage report from a specified folder,
    extracts key usage metrics, and emails the report to specified recipients. Supports both daily and monthly reports.
 
.PARAMETER Recipients
    A comma-separated list of email addresses to send the report to.
 
.PARAMETER Folder
    The folder where the Citrix license reports are stored.
 
.PARAMETER SmtpServer
    The SMTP server address used to send the email.
 
.PARAMETER ReportType
    Specifies whether to send a "Daily" or "Monthly" report.
 
.EXAMPLE
    Send-CitrixLicenseReport -Recipients "admin1@domain.com,admin2@domain.com" -Folder "C:\Reports\Citrix" -SmtpServer "smtp.company.com" -ReportType Monthly
 
    This example will send the monthly Citrix license usage report.
 
.EXAMPLE
    Send-CitrixLicenseReport -Recipients "admin1@domain.com,admin2@domain.com" -Folder "C:\Reports\Citrix" -SmtpServer "smtp.company.com" -ReportType Daily
 
    This example will send the daily Citrix license usage report.
#>

Function Send-CitrixLicenseReport {
    [CmdletBinding()]
    param (
        [Parameter(Mandatory = $true)]
        [string]$Recipients,

        [Parameter(Mandatory = $true)]
        [string]$Folder,

        [Parameter(Mandatory = $true)]
        [string]$SmtpServer,

        [Parameter(Mandatory = $true)]
        [ValidateSet("Daily", "Monthly")]
        [string]$ReportType
    )

    # Determine the report date format based on selection
    if ($ReportType -eq "Daily") {

      if ((Get-Date).DayOfWeek -eq "Monday") {
           $ReportDate = (Get-Date).AddDays(-3).ToString("yyyy-MM-dd")  # Get Friday's date
           Write-Host "`n[INFO] Today is Monday, picking Friday's report ($ReportDate)" -ForegroundColor Cyan
           $ReportPeriod = "Friday"
       } else {
           $ReportDate = (Get-Date).AddDays(-1).ToString("yyyy-MM-dd")  # Get Yesterday's date
           $ReportPeriod = "Yesterday"
       }
        
        $Subject = "Citrix Daily License Usage Report - $ReportDate"

    } else {
        $ReportDate = (Get-Date).AddMonths(-1).ToString("MMM-yyyy")
        $ReportPeriod = "LastMonth"
        $Subject = "Citrix Monthly License Usage Report - $ReportDate"
    }

    # Determine the current logged-in user and construct the email address
    $UserName = $env:USERNAME
    $Domain = $env:USERDOMAIN.ToLower() #$env:USERDNSDOMAIN
    $FromAddress = "$UserName@$Domain.com"

    # Validate if FromAddress is valid
    if (-not $FromAddress -or $FromAddress -eq "@.com") {
        Write-Host "Warning: Could not determine the sender email address. Using default." -ForegroundColor Yellow
        $FromAddress = "noreply@$Domain.com"
    }

    # Display name for the email sender
    $FromDisplayName = "Citrix License Automation Alert"

    

    # Get the latest report file based on Daily or Monthly selection
    $file = Get-ChildItem -Path $Folder -Filter "*$ReportDate*.xlsx" | Sort-Object LastWriteTime -Descending | Select-Object -First 1

    if (-not $file) {
        Write-Host "No report found for $ReportDate in $Folder" -ForegroundColor Yellow
        return
    }

    # Import data from the latest report
    try {
        $data = Import-Excel -Path $file.FullName
        $MaxValueT = $data.TotalLicenses[0]
        $MaxValue = $data.Licensesinuse[0]
        $MaxValueP = $data.Percentageused[0]
        [int]$MaxValueA = $MaxValueT - $MaxValue
    } catch {
        Write-Host "Error: Failed to read the Excel file: $($_.Exception.Message)" -ForegroundColor Red
        return
    }

    # Adjust report message based on report type
    if ($ReportType -eq "Daily") {
        $UsageMessage = "Yesterday, we reached a peak of <span style='color:Red;'><strong>$MaxValue</strong></span> consumed licenses."
    } else {
        $UsageMessage = "We reached a peak of <span style='color:Red;'><strong>$MaxValue</strong></span> consumed licenses for $ReportDate."
    }

    # Email Body (HTML)
    $Body = @"
        <html>
        <body>
            <p>Hi All,</p>
            <p>Attached is the Citrix license usage report for <strong>$ReportPeriod</strong>.</p>
            <p>$UsageMessage</p>
 
            <table border='1' cellpadding='5' cellspacing='0' style='border-collapse:collapse;'>
                <tr><td><strong>Installed Licenses</strong></td><td style='color:Green;'>$MaxValueT</td></tr>
                <tr><td><strong>Licenses in Use</strong></td><td style='color:Blue;'>$MaxValue</td></tr>
                <tr><td><strong>Licenses Available</strong></td><td style='color:Indigo;'>$MaxValueA</td></tr>
                <tr><td><strong>Percentage Used</strong></td><td style='color:Red;'>$MaxValueP</td></tr>
            </table>
 
            <br>Thanks!<br>
            <p>Regards,<br>Citrix VDI Support Team</p>
            <hr>
            <i>"Please Note: This is an automatically generated email, please do not reply."</i>
        </body>
        </html>
"@


    # Convert recipients string into an array
    $ToAddress = $Recipients -split ','

    # Send Email
    try {
        Send-MailMessage -To $ToAddress `
                         -From "$FromDisplayName <$FromAddress>" `
                         -Subject $Subject `
                         -Body $Body `
                         -BodyAsHtml `
                         -SmtpServer $SmtpServer `
                         -Priority High `
                         -Attachments $file.FullName
        Write-Host "Email sent successfully to: $Recipients" -ForegroundColor Green
    } catch {
        Write-Host "Error: Failed to send email: $($_.Exception.Message)" -ForegroundColor Red
    }
}