Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return count of items deleted using Get-ChildItem with Remove-Item

Tags:

powershell

I am successfully deleting files as expected using the below command; however, I'd like to get a count of the items deleted.

Get-ChildItem $dPath -Filter "*.blah" | Remove-Item 

I've tried this. It always deletes the file but the Measure-Object runs after the delete so 0 is always returned as the count

Get-ChildItem -Path C:\Temp -Filter "*.blah" | Remove-Item | Measure-Object

I've then tried it in reverse but always get:

[Remove-Item], ItemNotFoundException

Get-ChildItem -Path C:\Temp -Filter "*.blah" | Measure-Object | Remove-Item
like image 240
PseudoToad Avatar asked Dec 19 '25 06:12

PseudoToad


1 Answers

Collect the items in a variable, get the count of that list, then remove the items:

$items = Get-ChildItem -Path C:\Temp -Filter "*.blah"
$cnt   = $items.Count
$items | Remove-Item

or count the items that were successfully deleted:

$cnt = 0
Get-ChildItem -Path C:\Temp -Filter "*.blah" | ForEach-Object {
  Remove-Item $_.FullName
  if ($?) { $cnt++ }
}
like image 77
Ansgar Wiechers Avatar answered Dec 21 '25 21:12

Ansgar Wiechers



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!