A common task, especially during the development of specific filesystem tasks in a script, is to find and list all files that are larger than a specific file size in folder (and subfolders); in the following example we will find files larger than 500 MB in the entire C:\ drive.
Powershell
Get-ChildItem C:\ -recurse | where-object {$_.length -gt 524288000} | Sort-Object length | ft fullname, length -auto
This Powershell command will act to C:\ folder in the following way:
- -recurse parameter is used to find files stored in all sub-directories recursively. To find files only in the main folder you can remove this parameter.
- where-object {$_.length -gt 524288000} is our filter. It collects only those files that are greater than 500MB, while ignoring the rest. Size is in bytes. If you’d like to do the opposite, i.e., find files smaller than 500MB, then use the -lt parameter.
- Sort-Object length sorts result in ascending (default) order by length. To sort in descending order use this: Sort-Object length -descending.
- ft fullname, length -auto: ft or Format-Table is used to format the result. -auto prevents the output from spreading to the full width of the window, and consequently making the result easier to read. Run get-childitem | get-member to see other properties.
Another way to find larger files with a specific size is the following (where the size is defined by dividing the lenght of the file by 1GB (for Gigabytes) and the formatting the output with ToString method, .Tostring("0.00")):
Get-ChildItem -path c:\mydata -recurse | Where-Object { ($_.Length /1GB) -gt 2 } | ForEach-Object { ($_.length/1GB).Tostring("0.00") }
If you’re interested only in a specific file type, specify it this way in the command:
Get-ChildItem C:\ -recurse -include *.exe
Windows Command Prompt
In Command Prompt, so in batch and command files, forfiles command is used for batch processing a command on a file or set of files. The following command will find and list all files that are larger than 500MB in the C:\ drive.
forfiles /P C:\ /M *.* /S /C "CMD /C if @fsize gtr 524288000 echo @PATH @FSIZE"
The explanation of the above command is specified below:
- /P (Path): Specifies the path to process. If ignored, process starts in the current working directory.
- /M (Mask): Specifies the search filter. Example, for executables use *.exe.
- /S (Sub-Directories): Search for files in sub-directories recursively.
- /C (Command): Runs the specified command enclosed in quotation marks on each file.
- @PATH: Is a variable. It shows the full path of the file.
- @FSIZE: Shows the file size, in bytes.
To see list of other parameters and variables, simply enter forfiles /? in the command-line. This will help you to expand and format the output.