I wrote this script for https://github.com/sietsevdschoot/CreateTempDrive, it creates a drive based on a temporary folder. All contents in that folder will be automatically removed after a certain retention periond.
This scripts runs daily to clean a folder of all items which are older than the retention period. It will also delete any empty folders that deleting the files have caused. It supports an optional rundate and the generic -whatif and -confirm parameters.
This way you can see which files and folders will be removed in a folder when you run the command on a certain date.
[CmdletBinding(SupportsShouldProcess)]
param (
[Parameter(Mandatory)]
[IO.DirectoryInfo] $path,
[TimeSpan] $retentionPeriod = [TimeSpan]::FromDays(14),
[DateTime] $now = [DateTime]::MinValue
)
if ($now -eq [DateTime]::MinValue) {
$now = (Get-Date)
}
$oldFiles = Get-ChildItem $path.FullName -Recurse -File | ?{ $_.LastWriteTime -lt $now.Subtract($retentionPeriod) }
$folders = Get-ChildItem $path.FullName -Recurse -Directory
$emptyFolders = $folders `
| ?{ (Get-ChildItem $_.FullName -file -Recurse | ?{ $_.LastWriteTime -gt $now.Subtract($retentionPeriod) }) -eq $null } `
| Sort-Object -Property @{ Expression={ $_.FullName.Split([IO.Path]::DirectorySeparatorChar).Count }; Descending=$true }
$oldFiles | Remove-Item -Force
$emptyFolders | Remove-Item -Force -Recurse