首页 > 解决方案 > 解析日志文件并提取powershell

问题描述

我在日志文件中有这个,我只想要新日志文件中没有(s)的时间或放入变量,感谢您的回复。

Fri Nov 02 13:47:07 2018  time =5.803s
Fri Nov 02 14:02:10 2018  time =7.082s 

我的代码

Get-Content "logfile.txt" |
    select-string -pattern "5" |
    foreach-object{
        write-Output $_ >> "C:\Users\titi\Desktop\test.txt"
    }

标签: powershellvariableslogfile

解决方案


这将获得您似乎想要的信息... []

# fake reading in a text file
#    in real life, use Get-Content
$InStuff = @'
Fri Nov 02 13:47:07 2018 time =5.000s
Fri Nov 02 13:47:07 2018 time =5.803s
Fri Nov 02 14:02:10 2018 time =7.082s
Fri Nov 02 13:47:07 2018 time =4.000s
Fri Nov 02 13:47:07 2018 time =3.000s
Fri Nov 02 13:47:07 2018 time =5.001s
'@ -split [environment]::NewLine

$MinimumSeconds = 5.0

$Results = foreach ($IS_Item in $InStuff)
    {
    $Seconds = [decimal]($IS_Item.Split('=')[1].Trim().TrimEnd('s'))
    if ($Seconds -gt $MinimumSeconds)
        {
        $Seconds
        }
    }

''
$Results

输出 ...

5.803
7.082
5.001

上面发生了什么...

  • 在“=”上拆分
  • 取结果数组的第二部分
  • 修剪掉任何前导或尾随空格
  • 去掉结尾的's'
  • 转换为[decimal]
  • 与所需的最小值比较
  • 将剩余的号码发送到$Results集合
  • 显示它

将其保存回文件将使用 Set-Content。[咧嘴笑]


推荐阅读