We will continue to use the directory and the files we created for the book. If all of your files are of zero bytes, download a few files with content. The file type does not matter.
- List out the files in the directory.
PS> Get-ChildItem -Path .
- Filter the output to have only files.
PS> Get-ChildItem -Path . -File
- Pipe the object to the Sort-Object cmdlet to sort the output based on the file size.
PS> Get-ChildItem -Path . -File | Sort-Object -Property Length
- The shorthand for the expression would be:
PS> gci . -File | sort Length
- Sort the files, the largest file to the smallest file.
PS> Get-ChildItem -Path . -File | Sort-Object -Property Length -Descending
- Pick the largest three files in the lot.
PS> Get-ChildItem -Path . -File | Sort-Object -Property Length -Descending -Top 3
- Create two files, and, using a text editor, add some content into both of them. (Or use the following script block to create some random text.)
PS> $($i = 0; while ($i -lt 520) {(-join ((65..90) + (97..122) | Get-Random -Count 8 | ForEach-Object {[char]$_})).ToString(); $i++}) -join ' ' | Out-File ./random-text-1.txt; Start-Sleep -Seconds 60; $($i = 0; while ($i -lt 500) {(-join ((65..90) + (97..122) | Get-Random -Count 8 | ForEach-Object {[char]$_})).ToString(); $i++}) -join ' ' | Out-File ./random-text-2.txt
- Now, sort the files in the directory, first, by size, and then, the name.
PS> Get-ChildItem -Path . -File | Sort-Object -Property Length, Name
Observe the output that you get.
- Sort the list in the descending order.
PS> Get-ChildItem -Path . -File | Sort-Object -Property Length, Name -Descending