Author Posts

October 31, 2016 at 4:20 pm

I am trying to find files from the previous day in order to archive them. the below code is an attempt to do that but it returns all the files from yesterday and the ones created today. Thoughts on how to limit scope to a single day would be very helpful

$log_files=Get-ChildItem [DIR_PATH] -Recurse |Where-Object {$_.LastWriteTime -ge $yesterday -and $_.LastWriteTime -lt $today}

October 31, 2016 at 4:30 pm

You don't show how you derive $today but I suspect what you're doing is this
PS> Get-date

31 October 2016 16:24:19

PS> (Get-date).AddDays(-1)

30 October 2016 16:24:39

What you're getting is the files for the last 24 hours

You need to create explicit dates & times – for instance
PS> $start = Get-Date -Day 30 -Month 10 -Year 2016 -Hour 00 -Minute 00 -Second 00
PS> $end = Get-Date -Day 31 -Month 10 -Year 2016 -Hour 00 -Minute 00 -Second 00
PS> $start

30 October 2016 00:00:00

PS> $end

31 October 2016 00:00:00

And use those in your filter

October 31, 2016 at 5:31 pm

Awesome. You had it right. Thanks for the solution! (Was spinning my wheels)

October 31, 2016 at 5:40 pm

$yesterday = (get-date).date.adddays(-1)
$today = (get-date).date

November 1, 2016 at 11:32 am

That's a neater way of just getting the dates. Good one.

November 1, 2016 at 6:09 pm


This is what i usually do:

$files = Get-Childitem $dir -recurse | Where-Object { $_.LastWriteTime.Date -eq (Get-Date).Date.Adddays(-1)}

That way you get just the actual date from the LastWriteTime object aswell.