public/Message/Read-Message.ps1

using module '..\..\modules\Enums.psm1'
using module '..\..\modules\Helper\DateTimeHelper.psm1'
using module '..\..\modules\Session.psd1'

function Read-Message{
    [CmdletBinding()]
    [Alias('rdms')]
    param(
        [Parameter(Mandatory=$true)]
        # Audit log source file from where the messages will be loaded.
        [SOURCE] $source,
        # Requested messageId.
        [string] $id,
        # Referent message time taken as baseline from where the messages will be start analyzing.
        [string] $referentTime,
        # Timeframe in which the messages will be analyzed after the referent time.
        [string] $timeSpan,
        # Progress bar message
        [string] $progressMessage="Read $source messages...",
        [switch] $surpressOutToHost
    )

    #region Init

    if ([Session]::activeSessions.Count -eq 0){
        Write-Error $LocalizedData.NoActiveSessionMessage
        return
    }
    if (-not [Session]::getCurrent().canRead($source)){
        Write-Error $LocalizedData.BackgroundJobsStillActiveMessage
        return
    }

    $afterDateTime, $beforeDateTime = [DateTimeHelper]::getAfterBefore($referentTime, $timeSpan)
    if ($timeSpan -and -not $referentTime){ $referentTime = (now)}
    $hasReturn = $false

    $logFile = [Session]::getCurrent().auditLogFile
    $processor = [ProcessorFactory]::getBySource($source)

    $totalLines = $logFile.AssignFile($source)
    if($referentTime) {
        $count = $logFile.Seek($afterDateTime)
    }
    elseif ($id) {
        $count = $logFile.Seek($id)
    }
    else{
        $count = 0
    }

    #endregion

    while (-not $logFile.EOF()) {
        $line = $logFile.ReadLine()

        if ($line -and (-not $id -or ($id -and $line.id -eq $id)) -and ($line.created_at -lt $beforeDateTime)){
            $processor.ProcessMessage($line)
            $processor.ProcessCardinality($line)

            if ($processor.message) {
                Write-Output $processor.message
                $hasReturn = $true
            }
        }
        else { break }

        $count++
        $percentage = 100 * $count / $totalLines
        Write-Progress -Activity $progressMessage -PercentComplete $percentage
    }
    Write-Progress -Activity $progressMessage -Completed

    if (-not $hasReturn -and -not $surpressOutToHost){
        Write-Host $LocalizedData.NoOutputMessage -ForegroundColor Red
    }
}