PowerShell - Remove all lines of text file until a certain string is found

China☆狼群 提交于 2021-02-07 08:45:18

问题


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.

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.


回答1:


If you're running V4, you can use the array .Where() method, with the 'SkipUntil' option:

$content.Where({ $_ -like "*$lastweek*" },'SkipUntil')



回答2:


If you want to only keep the entries containing your specified search string from that log file, you can do something to the effect of:

$content = Get-Content $file | Where-Object {$_ -notcontains "$lastweek"} 
$content | Set-Content $file -force

Replace -notcontains "$lastweek" with -notlike "*$lastweek*" if needed for better matching.



来源:https://stackoverflow.com/questions/34141437/powershell-remove-all-lines-of-text-file-until-a-certain-string-is-found

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!