Set folder dates to newest file inside (using PowerShell)

Someone (not me this time) screwed up and while transferring content from old server to new one ended up messing all folder timestamps. Folders now have date when copy was made instead of preserving original dates as intended.


This is fairly typical problem after files are migrated without using Robocopy or using Robocopy but with wrong parameters.

Found this post from Internet that almost worked. Problem was empty folders weren't fixed. After some tinkering I came up with following script that worked for me. If you're lucky it might work for you as well.

# Only touch directories
$colFolder = Get-ChildItem -Recurse "c:\temp" | Where-Object {$_.mode -match "d"} | Sort-Object Fullname -Descending 
$VerbosePreference = "Continue"

# Let user know when we fail miserably
Foreach ($strFolder In $colFolder)
{
  Trap [Exception] {
  Write-Verbose "Failed:  $Folder"
  Continue
}

$Path = $strFolder.FullName
$Folder = Get-Item $Path

# Use time stamp from newest file or folder there is
If (-Not ($strNewestItem = Get-ChildItem $Path | Sort-Object LastWriteTime -Descending | Select-Object -First 1))
{
  # Seems this is empty directory so we go up and try to grab latest timestamp from there instead
  $DotDot=""
  Do
  {
    $DotDot=$DotDot+"\.."
    $strNewestItem = Get-ChildItem $Path$DotDot | Where-Object {$_.name -notmatch $strFolder} | Sort-Object LastWriteTime -Descending | Select-Object -First 1
    Write-Verbose "Whoopsie-doo, there's no files so have some dots instead: $DotDot"
  } 
  Until ($strNewestItem)
}
  
# Change the date to match the newest file or folder only if different than current
If ($strNewestItem.LastWriteTime -ne $Folder.LastWriteTime)
{
  $Folder.LastWriteTime = $strNewestItem.LastWriteTime}
  Write-Verbose "Changed: $Folder"
}

# EOF

Comments