Reset FOLDER Last Modified Date/Time

In NTFS (New Technology File System) many things will update the Last Modified date of a folder to Today/Now:

Being aware of such changes to the file system is valuable, but when the files have just been restored from a backup or moved to a new disk, the folders (but not the files) will all adopt dates reflecting the date of that server change.
It is often far more useful to reset each folder's date to reflect the date/time of the most recent file it contains.

The function below does just that, given a path to a folder it sets the folder Last Modified date to match the age of the newest file, it also recurses through any sub folders and sets those folder dates in the same way.

Because this has to compare the Last Modified date of every file, it can take some time to process a very large folder hierarchy.

When running this you may need to close any Windows Explorer sessions, as they will read and lock the Last Modified property.

Function Set-LastWrite {
    Param (
        [string] $path
    )

    # Variable to hold the newest file date/time
    $default = (Get-Date "01/01/1980 12:30 am")
    $newest = $default

    # Find the newest item in the folder (-force to include hidden files)
    Get-ChildItem -Path $path -Recurse -force | ForEach-Object {
        if ($_.PSIsContainer) {
            # Recurse into subfolder
            Set-LastWrite $_.fullname
 
            # Read the sub folder again in case its LastWriteTime has changed
            $sub = Get-Item -force -Path $_.fullname
            if ($sub.LastWriteTime -gt $newest) {
                $newest = $sub.LastWriteTime
            }
        }
        elseif ($_.LastWriteTime -gt $newest) {
            $newest = $_.LastWriteTime
        }
    }

    # Set the folder last modified date to match the age of the newest item
    if ($newest -gt $default) {
        $(Get-Item $path).lastwritetime = $newest
    }
    "Done: $path"
}

If you run this code against a large number of files that pre-date the year 2000, you may on occasion run into year 2000 bugs. It was not uncommon for some 90's era software to write files dates like 06/12/97
Those 2 digit years may in some circumstances get translated into 06/12/2097 and that will throw out the folder calculations.

To display a 4 digit year in Windows Explorer open Control Panel > Regional Settings > Date format > Short date > YYYY
The Touch script linked below can be used to fix any incorrect dates.

Example:

PS C:\> Set-LastWrite "C:\demo"

“Neither a wise man nor a brave man lies down on the tracks of history to wait for the train of the future to run over him” ~ Dwight D. Eisenhower

Related PowerShell Commands:

StampMe - Rename a file with the current Date/Time.
Touch - Change the date/time of a file/folder.
ROBOCOPY - Robust File and Folder Copy (CMD Shell)
Long Filenames - NTFS long filenames (>256 chars).


Copyright © SS64.com 1999-2019
Some rights reserved