deXterlab97
deXterlab97

Reputation: 135

Remove all files older than the specified one

I want to remove all txt extension file that has last write date older than the last write date of the current one (00007.txt is the current file) but can't figure out a way yet

$a = (get-item C:\Users\Jimmy\Desktop\test\*.txt).lastwritetime

$b = (get-item C:\Users\Jimmy\Desktop\test\00007.txt).lastwritetime


while ($a[$i] -lt $b)
{
$i++
remove-item $a
}

Upvotes: 0

Views: 41

Answers (2)

Esperento57
Esperento57

Reputation: 17462

Short version

$dt = (gi "C:\Users\Jimmy\Desktop\test\00007.txt").lastwritetime
gci "C:\Users\Jimmy\Desktop\test\" -file -Filter "*.txt" | ? LastWriteTime -lt $dt | ri

Upvotes: 0

Bacon Bits
Bacon Bits

Reputation: 32170

I would just enumerate the items with Get-ChildItem, filter with Where-Object, and pipe directly to Remove-Item:

$b = (get-item C:\Users\Jimmy\Desktop\test\00007.txt).lastwritetime

Get-ChildItem -Path C:\Users\Jimmy\Desktop\test\*.txt | Where-Object {
    $_.LastWriteTime -lt $b
} | Remove-Item;

Upvotes: 3

Related Questions