Question

I have the following line of code that will currently get the printer event logs for servers:

Get-EventLog -ComputerName ********* -LogName System -Source Print|where-object{$_.timeGenerated -gt (get-date "2013-03-11")}|select-object eventid,timegenerated,message |export-CSV -Path "C:\temp\export.csv"

At the moment, Get-Date works to get the printer logs for the specific day that I have written on the line of code. I'd like to alter this however in order to get printer logs for an entire week at a time. I was looking at TechNet's article on Get-Date, and I'm not seeing anything on how you can manage to specify that you would like to pull results from the previous week instead of a single day. How do I do this?

EDIT: Also, I'd like to find a way to where I don't have to specify specific dates. For example, I'd like to be able to get logs from this week, and then the following week get new logs, without having to alter the dates on the code.

Was it helpful?

Solution

I'm assuming that this is a follow-up to your previous post, Using WMI to get printer logs

As I noted in my answer to that question, you ought to be filtering at the source - Get-EventLog - instead of in a Where-Object. Get-EventLog provides two parameters for this - -Before and -After.

By filtering at the source, you will send a lot less data over the wire, which can be a significant performance improvement. It'll also reduce the time required by the remote system to process your request. Why ask for and retrieve data which you will discard without even looking at?

To get everything between one week ago and right now, do the following:

get-eventlog -computername ******* -logname system -after $((get-date).adddays(-7).date) -before $(get-date) -source Print | select-object eventid,timegenerated,message |export-CSV -Path "C:\temp\export.csv"

Change the values passed to -After and -Before as needed.

OTHER TIPS

Your Where-Object is only returning records greater than that date.

Where-Object { $_.timeGenerated -gt (get-date "2013-03-11") }

To get a date range try

Where-Object { $_.timeGenerated -gt [datetime]'2013-03-11' -and $_.timeGenerated -lt [datetime]'2013-03-18' }

This is basically saying: (lower bound) 2013-03-11 < (log entry generated date) < 2013-03-18 (higher bound)

Include another test in your where-statement. Like this:

Get-EventLog -ComputerName ********* -LogName System -Source Print |
where-object{$_.timeGenerated -gt ([datetime]"2013-03-11") -and $_.timeGenerated -lt ([datetime]"2013-03-18")} |
select-object eventid,timegenerated,message |
export-CSV -Path "C:\temp\export.csv"

It checks if the event is newer than 2013-03-11, but older than 2013-03-18.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top