Search code examples
powershellrecursionfile-ioget-childitem

Powershell: Recursively search a drive or directory for a file type in a specific time frame of creation


I am trying to incorporate Powershell into my everyday workflow so I can move up from a Desktop Support guy to a Systems Admin. One question that I encountered when helping a coworker was how to search for a lost or forgotten file saved in an unknown directory. The pipeline I came up with was:

dir C:\ -Recurse -Filter *.pdf -ErrorAction SilentlyContinue -Force | Out-File pdfs.txt

This code performed exactly how I wanted but now I want to extend this command and make it more efficient. Especially since my company has clients with very messy file management.

What I want to do with this pipeline:

  • Recursively search for a specific file-type that was created in a specified time-frame. Lets say the oldest file allowed in this search is a file from two days ago.
    • Save the file to a text file with the columns containing the Filename, FullName(Path), and sorted by the created time in descending order.

What I have so far:

dir C:\ -Recurse -Filter *.pdf -ErrorAction SilentlyContinue -Force | Select-Object Name, FullName | Out-File *pdfs.txt

I really need help on how to create a filter for the time that the file was created. I think I need to use the Where-Object cmdlet right after the dir pipe and before the Select Object pipe but I don't know how to set that up. This is what I wrote: Where-Object {$_.CreationTime <


Solution

  • You're on the right track, to get the files from a specific file creation date range, you can pipe the dir command results to:

    Where-Object {$_.CreationTime -ge "06/20/2017" -and $_.CreationTime -le "06/22/2017"}
    

    If you want something more repeatable where you don't have to hard-code the dates everytime and just want to search for files from up to 2 days ago you can set variables:

    $today = (Get-Date)
    $daysago = (Get-Date).AddDays(-2)
    

    then plugin the variables:

    Where-Object {$_.CreationTime -ge $daysago -and $_.CreationTime -le $today}
    

    I'm not near my Windows PC to test this but I think it should work!