Delete old files / Keep one for day
good morning guys,
i have big folder of logs files generate around 20 log file day.
i need delete everyday files older 14 days keep 1 day.
can me please?
thank , kind regards
we can use below function this
function remove-files { [cmdletbinding()] param ( [parameter(mandatory = $true)] [validatescript({ if ((test-path "$_") -eq $true) { $true } else { throw "folder cannot located" } })] [string]$folderpath ) dir -path "$folderpath" | { $_.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 | { $_.count -gt 1 } if ($groups) { foreach ($group in $groups) { ($group).group | sort lastwritetime -descending | select -skip 1 | remove-item -force -confirm:$false } } }use it:
remove-files -folderpath "full_path"function remove files older 14 days , keep single file per day
Windows Server > Windows PowerShell
Comments
Post a Comment