PowerShell Script Help - File Cleanup

DeaconFrost

[H]F Junkie
Joined
Sep 6, 2007
Messages
11,582
I'm not the greatest at writing PowerShell scripts, nor am I successful in finding an answer via Google. If Robocopy is better for this task, I'd gladly use that instead.

I want to schedule a task to run a script (easy part). The script in question need to hit a path, say C:\Build\Packages\ and delete any file over 45 days in age. Here's the caveat. I want it to only delete files beyond the initial 10 files that are 45 days in age. So, if I the directory only has 4 files, none are deleted, regardless of age. If the directory has 15 files, and all are less than 45 days old, none are deleted.

Is that possible with a PS script?
 
I did not check for the descending vs ascending that would be really important here (or if you need to use -44, 45 or 46), but something of the sorts ?

JavaScript:
$limit = (Get-Date).AddDays(-45)
$TargetFolder = "C:\yourPath\"
$files = Get-ChildItem $TargetFolder | Where-Object { !$_.PSIsContainer -and $_.CreationTime -lt $limit } | Sort-Object CreationTime  -Descending

# List Files
#$files

$count = 0
foreach ($i in $files)
{
    $count = $count+1
    if ($count -gt 10)
    {
        #echo " delete file"
        Remove-Item $TargetFolder\$i -recurse -force
    }
}

You can use lastwrite or lastread instead of creation time depending has well.

If should give you a list of only the files of 45 days ordered by their creation time, you skip the X more recent and delete after that, I imagine there is a simpler script way that a loop that could exist but I know very little in ps.
 
Last edited:
Clearly, you know much more than I do! Thanks! I'll give this a shot on a test set of files.
 
Back
Top