根据文本文件PowerShell中的时间戳删除行 [英] Delete lines based on time stamp in text file PowerShell
问题描述
此处的PS新手,但我有一个日志文件,其中每个条目都以以下日期格式写在单独的行上:2013-04-29 08:55:09,261
Novice at PS here, but I have a log file where each entry is written on a separate line with this date format: 2013-04-29 08:55:09,261
我正在尝试使用PowerShell删除所有30天以上的行.我一直在尝试使用某种大于代码的形式插入get-date -format"yyyy-MM-dd hh"输出,但是在这一点上,我只是在猜测.也一直尝试使用批处理文件创建forfile,但如果可以的话,我想坚持使用PS.
I am trying to use PowerShell to delete all lines older than 30 days. I have been trying to plug get-date -format "yyyy-MM-dd hh" output with some sort of greater than code, but at this point I’m just guessing. Also been trying forfiles with a batch file but would like to stick with PS if I can.
任何帮助将不胜感激.
推荐答案
假定文件包含以下内容:
Assuming a file with the contents:
2013-04-29 08:55:09,261 line1
2013-01-29 08:55:09,261 line2
2013-03-31 08:55:09,261 line3
对我来说,您的日期采用国际标准日期符号,因此您可以使用:
For me your dates are in the international standard date notation so you can just use :
$a = [datetime]"2013-04-29 08:55:09"
然后$a
将是日期,因此与文化无关.
Then $a
will be a date, so nothing to do with the culture.
您只需编写以下内容即可过滤日期中的所有行(此处为"2013-03-31")
You can just write the following to filter all lines from a date (here "2013-03-31")
get-content "C:\temp\date.txt" | where { [datetime]($_.split(','))[0] -ge "2013-03-31"}
我只是在昏迷上分割了行,将第一部分转换为日期后再进行比较.
I just split the line on the coma, take the first part and convert it to a date before compararing it.
对于您的30天,(get-date).date
给出不带小时的日期,而(get-date).date.adddays(-30)
给出不晚于今天的日期.
For your 30 days (get-date).date
give the date without hours and (get-date).date.adddays(-30)
give the date 30 days before today.
get-content C:\temp\date.txt | where { [datetime]($_.split(','))[0] -ge (get-date).date.adddays(-30)}
您可以将结果通过管道传输到新文件| set-content "C:\temp\newdate.txt"
You can pipe the result in a new file | set-content "C:\temp\newdate.txt"
这篇关于根据文本文件PowerShell中的时间戳删除行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!