我有一个应用程序可以创建以下格式的日志文件:
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脚本,该脚本将返回显示结果的表
我将其称为“高级”脚本,因为它可能包括:解析,格式化,创建新对象等
最佳答案
以下脚本可能会为您做到这一点... 如果您求助于合理的时间值...在一分钟内超过60秒是很奇怪的(这里给了我一些异常(exception),这些异常(exception)导致在日期/时间解析方面引起很多麻烦,直到我注意到为什么引发了异常...)
$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
}
}
}
但我发现它比第一种解决方案的可读性差得多(更不用说可维护性了)。这与日志文件的布局非常紧密地联系在一起。
关于powershell - PowerShell “Advance”解析以基于日志文件计算组件安装时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/692664/