PowerShell - 删除文本文件的所有行,直到找到某个字符串 [英] PowerShell - Remove all lines of text file until a certain string is found
问题描述
我目前有一个输出日志文件,它有点乱,而且增长很快.这是许可邮箱的大型脚本的调试输出.我基本上只想删除文件中的每一行,直到找到 7 天前日期的第一次迭代.
I currently have an output log file that's a bit of a mess and grows quickly. It's the debug output for a large script that permissions mailboxes. I basically just want to delete every line in the file until it finds the first iteration of the date 7days ago.
到目前为止,我可以返回包含该日期的所有行
So far, I can return all lines containing that date
$content = Get-Content $file
$lastweek = "{0:M/d/yyyy}" -f (get-date).AddDays(-7)
$content | Where-Object { $_.Contains("$lastweek") }
但是我想不出一个功能来擦除所有内容,直到第一次找到为止.
But I can not figure out a function to just wipe everything until that is found for the first time.
我试过 -replace:
I have tried a -replace:
$content -replace ".*$lastweek", " " | Set-Content $file -Force
但这似乎只是从包含指定字符串的每一行的开头替换.
But that only seems to replace from the beginning of each line that contains the specified string.
推荐答案
如果您运行的是 V4,则可以使用数组 .Where()
方法,以及 'SkipUntil
' 选项:
If you're running V4, you can use the array .Where()
method, with the 'SkipUntil
' option:
$content.Where({ $_ -like "*$lastweek*" },'SkipUntil')
这篇关于PowerShell - 删除文本文件的所有行,直到找到某个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!