user13988785
user13988785

Reputation: 3

PowerShell: How to use remove-item to delete files in batches?

I have a small script which deletes files from a directory where date1 is less than date2. My script is working, however, as this is run on a directory with many files, I'd like the remove item to only remove 100 files at a time, so that I can monitor the progress with each run. Is this possible?

 if ($date1 -lt $date2) 
                { 
                    $_ | Remove-Item;
               }

Upvotes: 0

Views: 2076

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174485

Use a for loop and make the counter step 100 on each iteration:

if($date1 -ge $date2){
  # nothing to be done
  return
}

$files = Get-ChildItem $pathToFolder

for($i = 0; $i -lt $files.Count; $i += 100){
    $null = Read-Host "Press Enter to delete the next 100 files... "
    $filesToDelete = $files[$i..($i+99)] 
    $filesToDelete |Remove-Item
    Write-Host "Deleted $($filesToDelete.Count) files..."
}

Upvotes: 1

Related Questions