Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PowerShell Remove Files smaller than 500bytes in directory recursively

Tags:

powershell

I need a script that will remove all files recursively in folders with an extension filter of .stat and all of which is smaller than 500bytes.

It would be nice if the script could first give me all files and the count of files that will be deleted and then with the hit of an enter it will proceed in deleting all files.

like image 954
user1702369 Avatar asked Jan 12 '15 08:01

user1702369


3 Answers

It's pretty straight forward with Get-Childitem, helped with Where-Object and ForEach-Object:

$path = 'some path defined here'
Get-ChildItem $path -Filter *.stat -recurse |?{$_.PSIsContainer -eq $false -and $_.length -lt 500}|?{Remove-Item $_.fullname -WhatIf}

Remove the -whatif once you have tested to make sure the code removes the files you want.

like image 51
Micky Balladelli Avatar answered Nov 09 '22 01:11

Micky Balladelli


If you have a large number of subfolders to recurse then you might want to try the -file switch for Get-ChildItem as filtering using the filesystem provider is more efficient than using Where-Object.

Get-ChildItem $path -Filter *.stat -recurse -file | ? {$_.length -lt 500} | % {Remove-Item $_.fullname -WhatIf}
like image 27
ConanW Avatar answered Nov 09 '22 01:11

ConanW


Simpler solution :

ls | where {$_.Length -lt .0.0005mb} | Remove-Item -Force-Recurse 
like image 1
Sid Avatar answered Nov 09 '22 03:11

Sid