public/Import-Log.ps1

FUNCTION Import-Log {
    <#
        .DESCRIPTION
        Imports and parses log files created with AMCScriptLog.
        .PARAMETER Path
        Array of files to import.
        .EXAMPLE
        PS> Import-Log -Path 'C:\Logs\Scripts\file.log'
        .EXAMPLE
        PS> $Files | Import-Log
        .EXAMPLE
        PS> Import-Log -Path @('C:\Logs\Scripts\file.log', 'C:\Logs\Scripts\file2.log')
        .NOTES
        Author: Adam Branham
        Date: 20240923
    #>

    [CmdletBinding()]
    PARAM(
        [Parameter(Mandatory = $true, ValueFromPipeline = $true)]
        [ValidateNotNullOrEmpty()]
        [string[]]$Path
    )

    BEGIN {
        $AllLogData = @()
    }

    PROCESS {
        FOREACH ($File in $Path) {
            IF (-not (Test-Path -Path $File)) {
                Write-Warning "File not found: $File"
                CONTINUE
            }

            TRY {
                $LogFile = Get-Item -Path $File
                $LogContent = Get-Content -Path $LogFile.FullName -ErrorAction Stop
            }
            CATCH {
                Write-Error "Failed to read file: $File. Error: $_"
                CONTINUE
            }

            $LogContentParsed = @()

            FOREACH ($Line in $LogContent) {
                IF ($Line -match 'File Date:\s*\[(.+?)\]') {
                    $LogDate = $Matches[1]
                }
                ELSEIF ($Line -match 'Log Name:\s*\[(.+?)\]') {
                    $LogName = $Matches[1]
                }
                ELSEIF ($Line -match 'Server:\s*\[(.+?)\]') {
                    $ServerName = $Matches[1]
                }
                ELSEIF ($Line -match 'RunAs:\s*\[(.+?)\]') {
                    $RunAs = $Matches[1]
                }
                ELSEIF ($Line -match '\[(\d{2}:\d{2}:\d{2}\s*[APM]{2})\]\[(\w{3})\]\s*(.+)') {
                    $LogContentParsed += [pscustomobject]@{
                        Time    = $Matches[1]
                        Type    = $Matches[2]
                        Message = $Matches[3]
                    }
                }
            }

            $LogContentMetaData = [pscustomobject]@{
                LogDate    = $LogDate
                LogName    = $LogName
                ServerName = $ServerName
                RunAs      = $RunAs
            }

            $AllLogData += [pscustomobject]@{
                FileName     = $LogFile.Name
                MetaData     = $LogContentMetaData
                Content      = $LogContentParsed
                FileFullName = $LogFile.FullName
            }
        }
    }

    END {
        # Control final output
        RETURN $AllLogData
    }
}