Delete all files smaller than x bytes size

This is more or less a reminder to myself, but could came handy for others as well.

I had a folder with 250k files, 80% are small files with 0-10k I wanted to delete.
The easiest thing that comes to mind in such a case: Sort the files by size in the Explorer and hit SHIFT + DEL.
The sad thing is, it does not work (or at least takes ages..)

In such situations is time to turn to the command line.

1. Deleting all smaller files than x with Cmd:

Move to the directory of choice and execute the following command to delete all files smaller than 2kb. Warning! Use with care and on your own risk!

@for /f  “dir /b *.HTM” do If %~zA LSS 2048 del %A

This works fine, if you suppress the output.
If you run it without the @ it is very slow.

2. Deleting all smaller files than x with PowerShell:

Move to the directory of choice (or define an explicit path instead of $path) and execute the following command to delete files smaller than 500kb.

Get-ChildItem $path -Filter *.html -recurse -file | ? {$_.length -lt 512000} | % {Remove-Item $_.fullname -WhatIf}

If you remove the -WhatIf parameter, and the command deletes for real, after you have tested to make sure the code removes the files you want. Again: Warning! Use on your own risk!

3. Count of all files in (current) directory

Since we are already here, we might also want to know how many files before/after in the directory (Explorer at least can handle this quite well).

(Get-ChildItem C:\Scripts).Count

or if we want to filter for a specific file type:

(Get-ChildItem C:\Scripts -filter “*.txt”).Count

Cmd can do this too, but again it can be slow:

dir /b /a-d | find /c /v “”

Here is a SO article that has some more suggestions how to delete files less than a specific size: https://stackoverflow.com/questions/6764621/delete-files-less-than-a-specific-size