PowerShell“Advance”解析以根据日志文件计算组件安装时间

时间:2009-03-28 11:57:15

标签: powershell scripting

我有一个创建以下格式的日志文件的应用程序:

2009-03-27 15:30:50 Start
2009-03-27 15:30:51 Starting Component 1 Installation
2009-03-27 15:30:52 blah
2009-03-27 15:30:53 blah
2009-03-27 15:30:54 blah
2009-03-27 15:30:55 ~~~ Finished Component 1 Installation ~~~
2009-03-27 15:30:56 Starting Component 2 Installation
2009-03-27 15:30:57 blah
2009-03-27 15:30:58 blah
2009-03-27 15:30:59 blah
2009-03-27 15:30:60 ~~~ Finished Component 2 Installation ~~~
2009-03-27 15:30:61 Starting Component 3 Installation
2009-03-27 15:30:62 blah
2009-03-27 15:30:63 blah
2009-03-27 15:30:64 blah
2009-03-27 15:30:65 ~~~ Finished Component 3 Installation ~~~
2009-03-27 15:30:66 Finished

我想你明白这个格式。

我想要实现的是拥有一个powershell脚本,它将返回一个结果表显示

  1. 组件名称
  2. 开始时间
  3. 结束时间
  4. 拍摄时间
  5. 我将其称为“高级”脚本,因为它可能包括:解析,格式化,创建新对象等等

    • 我是powershell的新手

1 个答案:

答案 0 :(得分:3)

以下脚本可能会为您做到这一点...... IF 您诉诸合理的时间值...一分钟内超过60秒是奇怪的(并且在这里给了我一些例外,导致日期/时间解析的主要问题,直到我注意到抛出异常的原因......)

$logfile = $args[0]

$log = get-content $logfile

$Components = @()

switch -regex ($log) {
    "(.*) Starting (.*) Installation" {
        $c = New-Object PSObject
        $st = [DateTime]::ParseExact($Matches[1], "yyyy'-'MM'-'dd HH':'mm':'ss", $null)
        $c | Add-Member -Type NoteProperty -Name Component -Value $Matches[2]
        $c | Add-Member -Type NoteProperty -Name StartTime -Value $st
    }
    "(.*) ~~~ Finished" {
        $et = [DateTime]::ParseExact($Matches[1], "yyyy'-'MM'-'dd HH':'mm':'ss", $null)
        $c | Add-Member -Type NoteProperty -Name EndTime -Value $et
        $c | Add-Member -Type NoteProperty -Name TimeTaken -Value ($c.EndTime - $c.StartTime)
        $Components += $c
    }
}

$Components

我可以使用以下代码将执行时间缩短一点(约25%):

$logfile = $args[0]

foreach ($l in Get-Content $logfile) {
    if ($l.Length -ge 30) {
        if ($l.Substring(20,8) -eq "Starting") {
            $c = New-Object PSObject
            $st = [DateTime]::ParseExact($l.Substring(0,19), "yyyy'-'MM'-'dd HH':'mm':'ss", $null)
            $c | Add-Member -Type NoteProperty -Name Component -Value $l.Substring(29, $l.Length - 42)
            $c | Add-Member -Type NoteProperty -Name StartTime -Value $st
        } elseif ($l.Substring(24,8) -eq "Finished") {
            $et = [DateTime]::ParseExact($l.Substring(0,19), "yyyy'-'MM'-'dd HH':'mm':'ss", $null)
            $c | Add-Member -Type NoteProperty -Name EndTime -Value $et
            $c | Add-Member -Type NoteProperty -Name TimeTaken -Value ($c.EndTime - $c.StartTime)
            $c
        }
    }
}

但我发现它比第一种解决方案更不易读(更不用说可维护)了。这与日志文件的布局非常严格地联系在一起。