# $share = "\\aps-mysql01.aps.local\RdpLog\$env:COMPUTERNAME"

# Megosztott mappa a szerver neve szerint
$share = "\\aps-mysql01.aps.local\RdpLog\$env:COMPUTERNAME"
if (-not (Test-Path $share)) {
    New-Item -Path $share -ItemType Directory -Force
}

# Funkció a logok kigyűjtésére
function Get-RDPEvents {
    param (
        [string]$LogName,
        [int[]]$EventIDs
    )

    Get-WinEvent -LogName $LogName |
        Where-Object { $_.Id -in $EventIDs } |
        ForEach-Object {
            $message = $_.Message
            $sessionID = $null
            $ursachencode = $null
            $userName = $null

            # 1️⃣ SessionID és Ursachencode regexből
            if ($message -match "Sitzung ""?(\d+)""?.*Ursachencode: (\d+)") {
                $sessionID = [long]$matches[1]
                $ursachencode = [long]$matches[2]
            }
            elseif ($message -match 'Sitzungs-ID:\s*(\d+)') {
                $sessionID = [long]$matches[1]
            }

            # 2️⃣ UserName: property[0]-ból
            if ($_.Properties.Count -ge 1 -and $_.Properties[0].Value -match "\S") {
                $userName = $_.Properties[0].Value
            }

            # 3️⃣ Ha nincs property-ben, Message-ből APS\ mintával
            if (-not $userName -and $message -match '(APS\\[^\s"]+)') {
                $userName = $matches[1]
            }

            # 4️⃣ 1149-es Event ID (auth) regex kiegészítés
            if (-not $userName -and $message -match 'Benutzer:\s*(\S+)') {
                $userName = $matches[1]
            }

            [PSCustomObject]@{
                ServerName   = $env:COMPUTERNAME
                LogName      = $LogName
                EventID      = $_.Id
                SessionID    = $sessionID
                Ursachencode = $ursachencode
                Level        = $_.LevelDisplayName
                UserName     = $userName
                Message      = $message
                TimeCreated  = $_.TimeCreated
            }
        }
}

# 1️⃣ UserName események (auth / reconnect) — SessionID-vel
$userEvents = Get-RDPEvents -LogName "Microsoft-Windows-TerminalServices-LocalSessionManager/Operational" -EventIDs 24,25,1149

# 2️⃣ Disconnect események
$disconnectEvents = Get-RDPEvents -LogName "Microsoft-Windows-TerminalServices-LocalSessionManager/Operational" -EventIDs 39,40

# 3️⃣ SessionID alapján hozzárendeljük a UserName-t a disconnect eseményekhez
$disconnectEvents | ForEach-Object {
    $matchingUser = $userEvents | Where-Object { $_.SessionID -eq $_.SessionID } | Sort-Object TimeCreated -Descending | Select-Object -First 1
    if ($matchingUser) { $_.UserName = $matchingUser.UserName }
}

# 4️⃣ Összesítés más logokkal
$remoteEvents = Get-RDPEvents -LogName "Microsoft-Windows-TerminalServices-RemoteConnectionManager/Operational" -EventIDs 1006,1026
$termDDEvents = Get-RDPEvents -LogName "System" -EventIDs 56 | Where-Object { $_.Message -like "*TermDD*" }
$brokerClientEvents = Get-RDPEvents -LogName "Microsoft-Windows-TerminalServices-SessionBroker-Client/Operational" -EventIDs 1000,1001
$brokerManagerEvents = Get-RDPEvents -LogName "Microsoft-Windows-TerminalServices-SessionBroker-Manager/Operational" -EventIDs 1000,1001

# 5️⃣ Összesítés
$allEvents = $userEvents + $disconnectEvents + $remoteEvents + $termDDEvents + $brokerClientEvents + $brokerManagerEvents

# CSV-be mentés
$filename = Join-Path $share ("RDP_Log_" + (Get-Date -Format "yyyyMMdd_HHmmss") + ".csv")
$allEvents | Export-Csv $filename -NoTypeInformation -Encoding UTF8

Write-Host "RDP log export kész: $filename"
