Public/ConvertFrom-NSPRdsEvent.ps1

function ConvertFrom-NSPRdsEvent {
    <#
    .SYNOPSIS
        Parses selected English RDS LocalSessionManager event messages.
    #>

    [CmdletBinding()]
    param([Parameter(Mandatory, ValueFromPipeline)][psobject]$InputObject)

    begin {
        $sessionPattern = 'Remote Desktop Services:\s*(?<RDSMessage>[^\r\n]+)\r?\n\r?\nUser:\s*(?<UserName>[^\r\n]+)\r?\nSession ID:\s*(?<SessionID>\d+)\r?\nSource Network Address:\s*(?<SourceIP>[^\r\n]+)'
        $arbitrationPattern = '(?<RDSMessage>[^\r\n]+):\r?\n\r?\nUser:\s*(?<UserName>[^\r\n]+)\r?\nSession ID:\s*(?<SessionID>\d+)'
        $definitions = @{
            21 = @{ Pattern = $sessionPattern; Description = 'Session Logon Succeeded' }
            24 = @{ Pattern = $sessionPattern; Description = 'Session disconnected' }
            25 = @{ Pattern = $sessionPattern; Description = 'Session Reconnection Succeeded' }
            40 = @{ Pattern = 'Session\s+(?<SessionID>\d+)\s+has been disconnected\.\s+reason code\s+(?<ReasonCode>\d+)'; Description = 'Session disconnected with reason code' }
            41 = @{ Pattern = $arbitrationPattern; Description = 'Begin session arbitration' }
        }
        $compiled = @{}
        foreach ($id in $definitions.Keys) {
            $compiled[$id] = New-Object System.Text.RegularExpressions.Regex($definitions[$id].Pattern, ([System.Text.RegularExpressions.RegexOptions]::Compiled), ([timespan]::FromSeconds(2)))
        }
    }
    process {
        if (-not $InputObject.PSObject.Properties['Id'] -or -not $InputObject.PSObject.Properties['Message']) {
            throw 'Each event must have Id and Message properties.'
        }
        $eventId = $InputObject.Id -as [int]
        if ($null -eq $eventId -or -not $compiled.ContainsKey($eventId)) { return }
        $match = $compiled[$eventId].Match([string]$InputObject.Message)
        if (-not $match.Success) { return }
        [pscustomobject]@{
            EventID = $eventId
            EventDescription = $definitions[$eventId].Description
            TimeCreated = if ($InputObject.PSObject.Properties['TimeCreated']) { $InputObject.TimeCreated } else { $null }
            UserName = $match.Groups['UserName'].Value
            SessionID = $match.Groups['SessionID'].Value
            SourceIP = $match.Groups['SourceIP'].Value
            RDSMessage = $match.Groups['RDSMessage'].Value
            ReasonCode = $match.Groups['ReasonCode'].Value
            _Raw = $InputObject
        }
    }
}