[CmdletBinding(SupportsShouldProcess = $true)] param( [Parameter(Mandatory = $true)] [string]$Destination, [string[]]$LogName = @('System', 'Application'), [int]$MaxEvents = 5000 ) $ErrorActionPreference = 'Stop' $destFull = [System.IO.Path]::GetFullPath($Destination) $stamp = Get-Date -Format 'yyyyMMdd-HHmmss' $targetRoot = Join-Path $destFull ('eventlogs-' + $stamp) if (Test-Path -LiteralPath $targetRoot) { throw "Destination already exists: $targetRoot" } if (-not $PSCmdlet.ShouldProcess($targetRoot, 'Export event logs')) { return } New-Item -ItemType Directory -Path $targetRoot -Force | Out-Null $manifest = New-Object System.Collections.Generic.List[object] foreach ($log in $LogName) { $safe = $log -replace '[^A-Za-z0-9._-]', '_' $file = Join-Path $targetRoot ($safe + '.csv') try { $events = @(Get-WinEvent -LogName $log -MaxEvents $MaxEvents -ErrorAction Stop) $selected = @($events | Select-Object TimeCreated, Id, LevelDisplayName, ProviderName, Message) if ($selected.Count -gt 0) { $selected | Export-Csv -LiteralPath $file -NoTypeInformation -Encoding UTF8 } else { Set-Content -LiteralPath $file -Value 'TimeCreated,Id,LevelDisplayName,ProviderName,Message' -Encoding UTF8 } $manifest.Add([pscustomobject]@{ Log = $log File = $file Events = $events.Count ExportedAt = (Get-Date) }) Write-Host "$log : $($events.Count) events" } catch { Write-Warning "Log $log skipped: $($_.Exception.Message)" } } $summaryPath = Join-Path $targetRoot 'summary.csv' if ($manifest.Count -gt 0) { $manifest | Export-Csv -LiteralPath $summaryPath -NoTypeInformation -Encoding UTF8 } else { Set-Content -LiteralPath $summaryPath -Value 'Log,File,Events,ExportedAt' -Encoding UTF8 } Write-Host "Folder: $targetRoot"