#Set the following to the days to keep value #and the directory value $daysToKeep = 34 $directory = 'B:\Backups\myBackups\' if (Test-Path $directory) { $olderThanDt = (Get-Date).AddDays(-$daysToKeep) $cntDel = 0 $cntLocked = 0 $strMsgFilesRemovedBase = "Total # Files Older Than ({0}) Days Successfully Deleted From Directory `"$directory`"`:" -f $daysToKeep $strLockedList = "" gci $directory | foreach { $curFullName = $_.Name $curLastWrite = $_.LastWriteTime if ((Test-Path $_.fullname -pathtype leaf) -and ($curLastWrite -lt $olderThanDt)) { try { [IO.File]::OpenWrite($_.FullName).close(); if ($curLastWrite -lt $olderThanDt) { $cntDel += 1 Remove-Item $_.fullname } } catch { $cntLocked += 1 if ($cntLocked -lt 11) { $strLockedList += "`nError: The Locked File `"$curFullName`" could not be deleted."} } } } if ($cntLocked -gt 0) { $cntLockedAddl = $cntLocked - 10 if ($cntLockedAddl -lt 0) { $cntLockedAddl = 0 } $strLockedList += "`nNote: $cntLockedAddl additional locked files could not be deleted." } if ($cntDel -gt 0) {write-output "$strMsgFilesRemovedBase $cntDel."} else {write-output "$strMsgFilesRemovedBase None Found."} if ($cntLocked -gt 0) { throw "Error: A total of $cntLocked File(s) Could Not Be Deleted. See the following output: $strLockedList `n$strMsgFilesRemovedBase $cntDel." } } else {throw "Error: Specified directory could not be accessed or does not exist."}