Find Files from yesterday

This topic contains 5 replies, has 4 voices, and was last updated by Profile photo of Kristoffer Berg Kristoffer Berg 1 month ago.

  • Author
    Posts
  • #56516
    Profile photo of Dennis
    DENNIS ROCHE
    Participant

    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

    $yesterday=(Get-Date).AddDays(-1)
    $log_files=Get-ChildItem [DIR_PATH] -Recurse |Where-Object {$_.LastWriteTime -ge $yesterday -and $_.LastWriteTime -lt $today}
    
  • #56522
    Profile photo of Richard Siddaway
    Richard Siddaway
    Moderator

    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

    • #56524
      Profile photo of Dennis
      DENNIS ROCHE
      Participant

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

  • #56525
    Profile photo of Ron
    Ron
    Participant

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

  • #56578
    Profile photo of Richard Siddaway
    Richard Siddaway
    Moderator

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

  • #56638
    Profile photo of Kristoffer Berg
    Kristoffer Berg
    Participant

    Hi!

    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.

You must be logged in to reply to this topic.