Change a folder LastWriteTime based on files within it
A few days ago I wrote a script that copies some files. Did notice that everything except the date on the folders were ok. So I added a few more lines of powershell code.
Did find a few suggestions on the web, but I like this one…. Since I wrote it. ![]()
Function Set-FolderDate {
Param (
[string] $Path
)
Trap [Exception] {
Write-Debug $("TRAPPED: " + $_.Exception.Message);
Write-Verbose "Could not change date on folder (Folder open in explorer?)"
Continue
}
# Get latest filedate in folder
$LatestFile = Get-ChildItem $Path | Sort-Object LastWriteTime -Descending | Select-Object -First 1
# Change the date, if needed
$Folder = Get-Item $path
if ($LatestFile.LastWriteTime -ne $Folder.LastWriteTime) {
Write-Verbose "Changing date on folder '$($Path)' to '$($LatestFile.LastWriteTime)' taken from '$($LatestFile)'"
$Folder.LastWriteTime = $LatestFile.LastWriteTime
}
Return $Folder
}
Set-FolderDate -Path "D:\temp"


