Powershell Remove Oldest Items
I am trying to use a do while loop to remove old files in a directory
(starting from the oldest) until there is one left, at which point the
program should end. The program should also only run if there is more than
one file in the directory at runtime.
I have semi-accomplished this using the following code:
$basedir = "C:\Test"
Set-Location -Path C:\Test
$a = Get-ChildItem -recurse $basedir
if ($a.Count -gt 1) {
do
{
$a | Sort-Object LastWriteTime -Descending | Select-Object -Last 1
| remove-item
}
while
(
$a.Count -gt 1
)
}
It will only run when there is more than one file present, which is correct.
It correctly deletes the oldest file, but then it keeps on trying to
delete the same file rather than rechecking the directory.
All I need help with at this point is getting it to re-run the loop once
it has deleted a file, rather than trying to delete the same file over and
over.
Thank you, sincerely, for any help and I apologise if this has been
answered before. I did a lot of searching but couldn't find something with
my situation.
Brad
No comments:
Post a Comment