Search code examples
powershellformattingtail

Powershell: Piping Get-Content -wait to an array of objects and redraw display table


I have a Powershell script that tails a log file using

Get-Content $logFile -wait | ForEach  { if ($_.Contains("[OK]")){ Write-Host -ForegroundColor Green $_ } elseif ($_.Contains("[FAIL]")){ Write-Host -ForegroundColor Red $_ } elseif ($_.Contains("[INFO]")){ Write-Host -ForegroundColor Yellow $_ } else { Write-Host $_ } } 

This logfile will never contain more than perhaps 100 lines that all relate to one of app. 15 services. Right now I just output those 100 lines to the screen using the above tail on the logfile.

But what I would really like to do is just show a table with 15 rows, and continuously update the table when I get a new line from the log to show new information when I get it from the log.

I have tried searching for examples of showing a table like that, but can't find any. Is it even possible and if it is, then I would appreciate a link to some info on it.


Solution

  • Each time you receive a message you could make an object and save it to an array. To re-output the table you would either need to display it line by line like you were or clear your host each time and output the entire object.

    $log = @()
    Get-Content $logFile -wait |
        ForEach-Object {
        switch ($_) {
            {$_.Contains("[OK]")} {
                $logentry = [pscustomobject]@{
                    'Status'  = 'Success'
                    'Message' = ($_ -split '\[OK\]')[-1]
                }
                $log += $logentry
            }
            {$_.Contains("[FAIL]")} {
                $logentry = [pscustomobject]@{
                    'Status'  = 'Failure'
                    'Message' = ($_ -split '\[FAIL\]')[-1]
                }
                $log += $logentry
            }
            {$_.Contains("[INFO]")} {
                $logentry = [pscustomobject]@{
                    'Status'  = 'Info'
                    'Message' = ($_ -split '\[INFO\]')[-1]
                }
                $log += $logentry
            }
            default {
                $logentry = [pscustomobject]@{
                    'Status'  = 'Unknown'
                    'Message' = $_
                }
                $log += $logentry
            }
        }
        Clear-Host
        foreach ($logentry in $log) {
            switch ($logentry.Status) {
                'Success' { Write-Host -ForegroundColor Green $logentry }
                'Failure' { Write-Host -ForegroundColor Red $logentry }
                'Info' { Write-Host -ForegroundColor Yellow $logentry }
                default { Write-Host $logentry }
            }
        }
    }
    
    $log | Export-CSV C:\Example\path.csv -NoTypeInformation