Powershell:将多个查询应用于日志中的foreach

时间:2018-06-29 13:51:44

标签: regex powershell

我需要从多个日志文件中获取总数据传输值。数据值显示在字节行的total列下。

它也分别用gmtk分隔,以显示gb / mb / tb / kb。

           Total    Copied   Skipped  Mismatch    FAILED    Extras
Bytes :  54.414 g  54.414 g         0         0         0         0

当前,我有此脚本,该脚本可以遍历所有文件并提取Bytes:g之间的值,但是我需要能够向`foreach文件中添加更多查询并求和它们全部变成一个一致的值。

这是我目前所拥有的,但是仅输出kb。

$pattern = "(?<=.*Bytes :.*)\w.+?(?= g.*)"
$pattern1 = "(?<=.*Bytes :.*)\w.+?(?= m.*)"
$pattern2 = "(?<=.*Bytes :.*)\w.+?(?= k.*)"

Get-ChildItem "C:\Users\logs" -Filter "BFR*" | ForEach-Object { 
    Get-Content "C:\Users\logs\*.log" | where-Object {$_ -match $pattern } | ForEach-Object {
        [double] ($matches[0])
    } | Measure-Object -Sum | Select-Object -ExpandProperty sum
} | ForEach-Object {
    Get-Content "C:\Users\logs\*.log" | where-Object {$_ -match $pattern1 } | ForEach-Object {
        [double] ($matches[0])
    } | Measure-Object -Sum | Select-Object -ExpandProperty sum
} | ForEach-Object {
Get-Content "C:\Users\logs\*.log" | where-Object {$_ -match $pattern2 } | ForEach-Object {
        [double] ($matches[0])
    } | Measure-Object -Sum | Select-Object -ExpandProperty sum
}

1 个答案:

答案 0 :(得分:1)

这是一种可能性。 (对不起,@ JamesC,它是1线:-)):

Get-ChildItem .\LogFolder\*.log |
    ForEach-Object {$totalBytes = 0}{
        Get-Content $_ | Select-String -Pattern "^Bytes\s+:\s+(?<size>\d+\.\d+) (?<units>[tgmk]).*$" | 
            Foreach-Object {
                $size = $_.Matches.Groups[1].Value

                switch ($_.Matches.Groups[2].Value)
                {
                    t {$totalbytes += (1tb * $size)}
                    g {$totalbytes += (1gb * $size)}
                    m {$totalbytes += (1mb * $size)}
                    k {$totalbytes += (1kb * $size)}
                }
            }
    } {"Total Bytes: $totalBytes"}