PowerShell: How to Sort Files in Folder by Size


You can use the following syntax in PowerShell to sort all files in a folder by size:

Get-ChildItem -File -Recurse |
    Select-Object -Property Length, Name |
    Sort-Object -Property Length |
    Format-Table -AutoSize

This particular example will display all files in the current directory and all subfolders, sorted in ascending order by file size.

The following example shows how to use this syntax in practice.

Example: Use PowerShell to Sort Files in Folder by Size

We can use the Get-ChildItem cmdlet to first view all files in our current directory:

We can see that there are four total files in the current directory.

Suppose that we would like to display each of these files sorted by size.

We can use the following syntax to do so:

Get-ChildItem -File -Recurse |
    Select-Object -Property Length, Name |
    Sort-Object -Property Length |
    Format-Table -AutoSize

The following screenshot shows how to use this syntax in practice:

PowerShell sort files by size

The files are sorted by size from smallest to largest.

Note that you can also use the -Descending parameter with the Sort-Object cmdlet to instead sort the files in order by size from largest to smallest:

Get-ChildItem -File -Recurse |
    Select-Object -Property Length, Name |
    Sort-Object -Property Length -Descending |
    Format-Table -AutoSize

The following screenshot shows how to use this syntax in practice:

PowerShell sort files by size in descending order

The files are now sorted by size from largest to smallest.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to List Files in Directory by Date
PowerShell: How to Get Most Recently Modified File in Directory
PowerShell: How to List All Files in Directory to Text File
PowerShell: How to Delete All Files with Specific Extension

Leave a Reply