Search code examples
powershellloopsrecursionforeachreport

How do I write a Powershell script that checks when the last time a file was added to a folder?


I'm currently writing a script that checks each folder in a directory for the last time a file was written to each folder. I'm having trouble figuring out how to obtain the last time a file was written to the folder, as opposed to just retrieving the folder's creation date.

I've tried using Poweshell's recursive method, but couldn't figure out how to properly set it up. Right now, the script successfully prints the name of each folder to the Excel spreadsheet, and also print the last write time of each folder, which is the incorrect information.

$row = 2

$column = 1

Get-ChildItem "C:\Users\Sylveon\Desktop\Test"| ForEach-Object {     

    #FolderName
    $sheet.Cells.Item($row,$column) = $_.Name
    $column++
    #LastBackup
    $sheet.Cells.Item($row,$column) = $_.LastWriteTime
    $column++
    #Increment to next Row and reset Column
    $row++
    $column = 1
}

The current state of the script prints each folder name to the report, but gives the folders creation date rather than the last time a file was written to that folder.


Solution

  • If you're only looking at the first level of files in each folder, you can do it using a nested loop:

    $row = 2
    $column = 1
    
    $folders = Get-ChildItem $directorypath
    ForEach ($folder in $folders) { 
    
        # start off with LastEdited set to the last write time of the folder itself
        $LastEdited = $folder.LastWriteTime
        $folderPath = $directoryPath + '\' + $folder.Name
        # this 'dynamically' sets each folder's path
    
        $files = Get-Childitem $folderPath
        ForEach ($file in $files) {
            if ((Get-Date $file.LastWriteTime) -gt (Get-Date $LastEdited)) {
                $LastEdited = $file.LastWriteTime
            }
        }
    
        $sheet.Cells.Item($row,$column) = $folder.Name
        $column++
        $sheet.Cells.Item($row,$column) = $LastEdited
        $row++
        $column = 1
    }