【问题标题】:Powershell: Piping Get-Content -wait to an array of objects and redraw display tablePowershell:管道获取内容 - 等待对象数组并重绘显示表
【发布时间】:2017-09-22 12:02:20
【问题描述】:

我有一个 Powershell 脚本,它使用

来跟踪日志文件
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 $_ } } 

此日志文件将永远不会包含超过 100 行的所有与应用程序之一相关的行。 15 项服务。现在我只是在日志文件中使用上面的尾部将这 100 行输出到屏幕上。

但我真正想做的只是显示一个有 15 行的表,并在我从日志中获取新行时不断更新表,以便在我从日志中获取新信息时显示新信息。

我已尝试搜索显示此类表格的示例,但找不到任何示例。是否有可能,如果有,我将不胜感激提供一些相关信息的链接。

【问题讨论】:

  • 老实说……我不确定你想做什么……
  • 显示一些状态信息并随着状态变化而变化的表格。不仅仅是将状态更改列为文本行。

标签: powershell formatting tail


【解决方案1】:

每次收到消息时,您都可以创建一个对象并将其保存到数组中。要重新输出表格,您要么需要像以前一样逐行显示它,要么每次都清除主机并输出整个对象。

$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

【讨论】:

  • 谢谢...这正是我想要的。
猜你喜欢
  • 1970-01-01
  • 2010-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-16
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多