Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources: Active Threads
Viewing all articles
Browse latest Browse all 8411

Deleting every other file in directory with name signature

$
0
0

I'm trying to thin out backup files.  We are accumulating too many backups but want to keep every other one older than a certain age.

For some reason, I get the files I need in my GetChildItem, but I'm trying to save them to an array and I'm having trouble using a for loop on the array so I can access every other one for deletion. This was easier when I was just deleting all files older than a certain age because I was using Remove-Item with my GetChildItem selection. Deleting every other one is tougher.

The code looks like this:

$Drive = "E:\temp\"

$deleteTime = -42;

$limit = (Get-Date).AddDays($deleteTime)

#this is finding the correct files but I don't think it's really in an array

(array)$temp1 = @(Get-ChildItem -Path $Drive -filter "*junk.vhd*" | Where-Object {$_.LastWriteTime - lt $limit} | Foreach-Object {$_.Name} )

#check that we can remove every other one with for loop

for($i=$temp1.GetLowerBound(0); $i -le $temp1.GetUpperBound(0); $i+=2) {

   Write-Host "removing $temp1[$i]"  #this is listing the entire array with a [0] for first one

}


Viewing all articles
Browse latest Browse all 8411

Latest Images

Trending Articles



Latest Images