Quantcast
Channel: Windows PowerShell forum
Viewing all articles
Browse latest Browse all 21975

Delete files older than 24 hours

$
0
0

Hi guys,

with your help I created this script that delete from a folder all the files older than 14 days and keep just 1 for day from today to 14 days ago.

I need that ALL the files in the last 24 hours are not going to be deleted.

So, I need to have a folder with ALL the files in the last 24 hours, just 1 file from 24 hours ago to 14 days ago, and all the others deleted.

I attach you the script. Can you help me?

Thank you very much everyone

function remove-oldfiles
{
[CmdletBinding()]
Param (
[Parameter(Mandatory = $true)]
[ValidateScript({
if ((Test-Path "$_") -eq $true) { $true }
else { Throw "folder cannot be located" }
})]
[string]$FolderPath
)
dir -Path "$FolderPath" | where { $_.LastWriteTime -lt ((Get-Date).AddDays(-14)) } | Remove-Item -Force -Confirm:$false
$remaingfiles = dir -Path "$FolderPath" | select *, @{ n = 'DayofFile'; e = { $_.lastwritetime.toshortdatestring() } }
$groups = $remaingfiles | Group-Object dayoffile | where { $_.count -gt 1 }
if ($groups)
{
foreach ($group in $groups)
{
($group).group | sort lastwritetime -Descending | select -Skip 1 | Remove-Item -Force -Confirm:$false
}
}
}


Viewing all articles
Browse latest Browse all 21975

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>