3

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.

Justin
  • 33
  • 1
  • 3

2 Answers2

8

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

$content.Where({ $_ -like "*$lastweek*" },'SkipUntil')
mjolinor
  • 66,130
  • 7
  • 114
  • 135
  • That throws a Method error: "Method invocation failed because [System.String] does not contain a method named 'like'" I got it to work with: `$content.Where({ $_ -like ("*$lastweek*") },'SkipUntil')` Thank you. – Justin Dec 07 '15 at 20:00
  • My fault. I'll fix the answer. – mjolinor Dec 07 '15 at 20:16
1

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.

bentek
  • 235
  • 1
  • 9
  • In my situation, I wanted to keep everything after the first iteration of that string. There are entries in the file on the hour all day long, so I didn't want to lose everything in between the lines with that date. Appreciate the response, though. – Justin Dec 07 '15 at 20:41