Andrew Tobey
Andrew Tobey

Reputation: 923

Parsing lines no older than a specific date

I am working on some PowerShell scripting stuff not having a strong PowerShell skill under my belt. Basically I am more into Java, but I need to use PowerShell to get some things done at work.

What I have so far is a little snippet that parses my desired log file, returns an object and writes it to a file.

# find all lines with "successfully installed":
Select-String -Path $env:windir\WindowsUpdate.log -Pattern 'successfully installed' |
 ForEach-Object {
   $information = $_ | Select-Object -Property Date, Product
   $parts = $_.Line -split '\t'
   [DateTime]$information.Date = $parts[0] + ' ' + $parts[1].SubString(0,8)
   $information.Product = ($_.Line -split 'following update: ')[-1]
   $information
  } | Out-File parsedUpdate.log 

My output looks like this enter image description here

What I would love to do next is to

  1. Get rid of the line that labels the Properties and the line below it as well as I would send the output to EventLog soon.

  2. Select only the lines that are no older than a specific date.

So how would I go about rejecting these two lines? Regarding the date problem I would love the exclude lines older than a specific date which I specify.

I have read that that Select-String has an -Exclude <String> property.

Would it be smart (and of course possible) to use this Directive to Exclude lines with a specific date and how would I do that - lets say for example, to reject any line older than a week from now?

thanks in advance.

Andrew

Upvotes: 0

Views: 1175

Answers (2)

mjolinor
mjolinor

Reputation: 68263

The timestamps on the actual log entries are in string sortable format, so you can do your date filtering early, before object creation:

$Start = (get-date).AddDays(-7).ToString('yyyy-MM-dd')

Select-String -Path $env:windir\WindowsUpdate.log -Pattern 'successfully installed' |
Where {$_.line -gt $Start} |

Upvotes: 2

MatthewG
MatthewG

Reputation: 9293

All you have to do for the (2) part of your question is add a filter to your result set, since you've already got objects with the Date property. The filter clause will look like Where-Object { $_.Date -ge "2/6/2015" } just replace with the date you are interested in.

# find all lines with "successfully installed" no older than 2/6/2015:
Select-String -Path $env:windir\WindowsUpdate.log -Pattern 'successfully installed' |
 ForEach-Object {
   $information = $_ | Select-Object -Property Date, Product
   $parts = $_.Line -split '\t'
   [DateTime]$information.Date = $parts[0] + ' ' + $parts[1].SubString(0,8)
   $information.Product = ($_.Line -split 'following update: ')[-1]
   $information
  } | Where-Object { $_.Date -ge "2/6/2015" } | Out-File parsedUpdate.log 

Upvotes: 0

Related Questions