Reporting Exchange Mail Traffic and Login Statistics with PowerShell


 In today's work environments, email communication holds critical importance for organizations, creating the need to manage and track usage statistics. In this context, monitoring and reporting the access status and mail traffic of mailboxes on Exchange servers according to specific criteria is crucial for an Exchange administrator. In this blog post, I'll explain in detail how to use the PowerShell script below to collect mailbox access information and mail traffic, and transform this data into a meaningful report.

Script Structure

The script includes the following sections:

1. Adding Required PowerShell Snap-ins

Add-PSSnapin *Exchange*
The Add-PSSnapin *Exchange* PowerShell command is used to add the Exchange Management Shell (EMS) module.

2. Initializing Variables with Default Values

$global:LogonArray = @()
$global:LogonNullArray = @()
$progress = 0
In this section, global variables used during the script's execution are defined, and their initial values are set.

3. Function to Collect User Information

# Function to collect mailbox information
function getMbxLastLogon ($mailboxes) {
    foreach ($mailbox in $mailboxes) {
        $progress++
        $percentComplete = ($progress / $mailboxes.count) * 100

        # Show progress while collecting user information
        Write-Progress -PercentComplete $percentComplete -Status "Collecting user information, please wait... Progress: $([math]::Ceiling($percentComplete))%" -CurrentOperation "User: $($mailbox.SamAccountName)" -Activity "Mailbox Access"

        # Get mailbox and user information
        $mailboxInfo = Get-Mailbox -Identity $mailbox.Identity
        $userInfo = Get-ADUser -Identity $mailboxInfo.SamAccountName -Properties *

        # Get the count of emails sent since a specific date
        $messagecount = (Get-TransportService | Get-MessageTrackingLog -Sender $mailboxInfo.EmailAddresses.SmtpAddress -EventId SEND -Start $tarih).count

        # Create an object containing user information
        $userAttribute = [PsCustomObject]@{
            Number = $progress
            SamAccountName = $mailboxInfo.SamAccountName
            DisplayName = $mailboxInfo.DisplayName
            GivenName = $userInfo.GivenName
            SurName = $userInfo.Surname
            ComputerLastLogon = $userInfo.LastLogonDate
            ComputerLogonCount = $userInfo.logonCount
            MailLastLogon = $mailbox.LastLogonTime
            MailCount = $messagecount
        }

        # Update the global array
        $global:LogonArray += $userAttribute

        # Write information to the console
        Write-Host "$($mailbox.DisplayName) has sent $messagecount emails."

        # Operation completed
        Write-Progress -Completed -Activity "Mailbox Access Information"
    }
    $progress = 0
}
This function collects information for specified mailboxes and then adds this information to an array ($global:LogonArray). It also updates the progress bar and writes relevant user information to the console and progress bar.

4. Function to Collect Information for Mailboxes with No Access

# Function to collect information for mailboxes that have never been accessed
function getMbxLastLogonNull ($mailboxes) {
    foreach ($mailbox in $mailboxes) {
        $progress++
        $percentComplete = ($progress / $mailboxes.count) * 100

        # Show progress while collecting user information
        Write-Progress -PercentComplete $percentComplete -Status "Collecting user information, please wait... Progress: $([math]::Ceiling($percentComplete))%" -CurrentOperation "User: $($mailbox.SamAccountName)" -Activity "No Mailbox Access"

        # Get mailbox and user information
        $mailboxInfo = Get-Mailbox -Identity $mailbox.Identity
        $userInfo = Get-ADUser -Identity $mailboxInfo.SamAccountName -Properties *

        # Get the count of emails sent since a specific date
        $messagecount = (Get-TransportService | Get-MessageTrackingLog -Sender $mailboxInfo.EmailAddresses.SmtpAddress -EventId SEND -Start $tarih).count

        # Create an object containing information for a mailbox that has never been accessed
        $userAttribute = [PsCustomObject]@{
            Number = $progress
            SamAccountName = $mailboxInfo.SamAccountName
            DisplayName = $mailboxInfo.DisplayName
            GivenName = $userInfo.GivenName
            SurName = $userInfo.Surname
            ComputerLastLogon = $userInfo.LastLogonDate
            ComputerLogonCount = $userInfo.logonCount
            #MailLastLogon = $mailbox.LastLogonTime
            #MailCount = $messagecount
        }

        # Update the global null array
        $global:LogonNullArray += $userAttribute

        # Operation completed
        Write-Progress -Completed -Activity "Users with No Mailbox Access"
    }
    $progress = 0
}
Similarly, this function collects information for specified mailboxes with no access and adds it to the $global:LogonNullArray array.

5. HTML and CSS Styles

# HTML and CSS variables for reporting
$htmlHeader = @"
<style>
    h1 {
        color: #333;
    }

    h2 {
        color: #444;
    }

    table {
        font-size: 12px;
        border: 0px;
        padding: 4px;
        margin: 0px;
        border: 0;
    }

    th {
        background: #395870;
        background: linear-gradient(#49708, #293f50);
        color: #fff;
        font-size: 11px;
        padding: 10px 15px;
        vertical-align: middle;
    }

    tbody tr:nth-child(even) {
        background: #f0f0f2;
    }
</style>
"@
This block is used to determine the style of the HTML report. It defines style properties such as colors, sizes, and backgrounds for elements like headers (h1, h2), tables (table, th), and table rows (tbody tr:nth-child(even)). Including CSS style properties enhances customization of the report's appearance by incorporating them into the HTML document.

6. Getting the Start Date from the User

# Get date input from the user
$tarihInput = Read-Host "Please enter the start date. (MM/DD/YYYY Example: 09/15/2023)"

# Check the date format
if ($tarihInput -match "\d{2}/\d{2}/\d{4}") {
    # If the format is correct, assign it to the $tarih variable
    $tarih = [datetime]::ParseExact($tarihInput, "MM/dd/yyyy", $null)
    Write-Host "Entered date: $($tarih.ToString('MM/dd/yyyy'))"
} else {
    Write-Host "Invalid date format. Please enter a date in MM/DD/YYYY format."
}
In this code block, the date input received from the user using Read-Host undergoes a specific format check. If the user has entered a valid date format, it is converted to the $tarih variable. If the user has not entered a valid date format, an error message is displayed.

7. Organizational Unit (OU) Where Data is Collected

$OU = "example.tld/Departments/Users"
This variable specifies the organizational unit where the script will run. Replace this field with your own Organizational Unit.

8. Collecting Access Information for Mailboxes

$LogonTime = Get-Mailbox -OrganizationalUnit $OU -RecipientTypeDetails UserMailbox | Get-MailboxStatistics -WarningAction SilentlyContinue | Where-Object { $_.LastLogonTime -gt $tarih }
getMbxLastLogon $LogonTime
In this section, the process of collecting access information for mailboxes with access information after the specified date is performed.

9. Collecting Information for Users with No Access

$LogonNull = Get-Mailbox -OrganizationalUnit $OU -RecipientTypeDetails UserMailbox | Get-MailboxStatistics -WarningAction SilentlyContinue | Where-Object { $_.LastLogonTime -eq $null }
getMbxLastLogonNull $LogonNull
In this section, information for users who have never accessed their mailbox is collected.

10. Creating the HTML Report

$htmlbody = ($global:LogonArray | ConvertTo-Html) + "<h2>Users who have never accessed their mailbox:</h2></br >" + ($global:LogonNullArray | ConvertTo-Html)
$htmlreport = ConvertTo-Html -Body $htmlbody -Head $htmlHeader -PostContent "Number of users who logged into their mailbox $($LogonTime.count)</br > Number of users who did not log in $($LogonNull.count)"
$htmlreport > "<path>"
>
This script transforms the collected data into an HTML report and saves it to the "<path>" file. Specify the path where you want to save the report, including the report name and extension. For example, "C:\report.html".




    This script is designed to collect and meaningfully report on the access information of mailboxes on Exchange servers. I hope this article helps you understand the script's functionality and customize it according to your requirements.


Türkçe makaleye erişmek için lütfen tıklayın..

Yorumlar

Bu blogdaki popüler yayınlar

Exchange Server 2016/2019 Sertifika Yenileme

Bulk Resetting Active Directory User Passwords