Forum Discussion

Fred_Elmendorf's avatar
Fred_Elmendorf
Brass Contributor
Mar 08, 2023
Solved

Restricting PowerShell folder search to a specific date range

The help I've received here has been invaluable, and as expected, once something good has been accomplished, there are always new requirements. So... Thanks in advance for continuing to assist this P...
  • Varun_Ghildiyal's avatar
    Varun_Ghildiyal
    Mar 09, 2023

    Fred_Elmendorf 

     

    No problem! You can modify the script to count only the files that were created in 2023. Here's how you can do it:

     

     

    $dirs = Get-ChildItem "\\Myorg\firstlevel\secondlevel\thirdlevel\Ion" -Directory
    $csvLog = "\\Myorg\output\fileshare\mystuff\Documents\PowerShellOutput\Latest Ion Trend Files Size Counts.csv"
    
    $startDate = Get-Date "01/01/2023"
    $endDate = Get-Date "01/01/2024"
    
    foreach ($dir in $dirs) {
        $folder = $dir.Name
        $directory = $dir.FullName
        $filesCount = (Get-ChildItem $directory -Filter "trend*.pqd" -Recurse `
            | Where-Object { $_.CreationTime -ge $startDate -and $_.CreationTime -lt $endDate }).Count
        $object = New-Object -TypeName psobject
        $object | Add-Member -MemberType NoteProperty -Name "Site" -Value $folder
        $object | Add-Member -MemberType NoteProperty -Name "File Count" -Value $filesCount
        $object | Export-Csv $csvLog -Encoding ASCII -Append -NoTypeInformation
    }

     

     

    In the modified script, we are still iterating through the directories, but instead of counting and outputting the latest file, we are counting the number of files that were created in 2023. We achieve this by filtering the files based on their CreationTime property and checking if it falls within the startDate and endDate range.

    We then create a PowerShell object and add the Site name and the File Count for that directory, and then export it to a CSV file.

    Let me know if this solves your problem.

Resources