Page 1 of 1

script deleted newer files?

Posted: Fri Sep 01, 2023 3:11 pm
by gqninten
Hello All - appreciate the time. hope all is well. need some help in deciphering why a script deleted data when it shouldn't have. The script below is to look for files older than 3 years and then delete it based on LastWriteTime. However there were some files/folders which were modified last week but were deleted.

I thought maybe it's because the 2nd part of the script is to look for empty folders.. however there was content in the deleted folders. so not sure what to make of it.

Is my logic incorrect?



#####

$Folder = "D:\"



#Delete files older than 3 years

Get-ChildItem $Folder -Recurse -Force -ea 0 |

? {!$_.PsIsContainer -and $_.LastWriteTime -lt (Get-Date).AddDays(-1095)} |

ForEach-Object {

$_ | del -Force -Recurse -Confirm:$false

$_.FullName | Out-File C:\data\3years+-D_Drive.txt -Append

}



#Delete empty folders and subfolders

Get-ChildItem $Folder -Recurse -Force -ea 0 |

? {$_.PsIsContainer -eq $True} |

? {$_.getfiles().count -eq 0} |

ForEach-Object {

$_ | del -Force -Recurse -Confirm:$false

$_.FullName | Out-File C:\data\3years+-D_Drive.txt -Append

}