🎓 A1Learner
🔍
0 of 52 lessons completed

PowerShell Listing and Filtering

Listing and filtering means showing only the files you want from a folder. A cmdlet is a small built-in command, and Get-ChildItem is the cmdlet that lists files.

List only text files

Create three files first, then list only the ones ending in .txt. Sorting by name keeps the order steady.

Set-Content -Path "apple.txt" -Value "apple"
Set-Content -Path "banana.txt" -Value "banana"
Set-Content -Path "notes.log" -Value "note"
Get-ChildItem -Filter "*.txt" | Sort-Object Name | Select-Object -ExpandProperty Name

Narrow a listing with Where-Object

Where-Object is a cmdlet that keeps only items passing a test. Here it keeps only names starting with b.

Set-Content -Path "apple.txt" -Value "apple"
Set-Content -Path "banana.txt" -Value "banana"
Set-Content -Path "berry.txt" -Value "berry"
Get-ChildItem -Filter "*.txt" | Where-Object { $_.Name -like "b*" } | Sort-Object Name | Select-Object -ExpandProperty Name

Count the matching files

Measure-Object is a cmdlet that counts results. Read its Count property to print just the number.

Set-Content -Path "apple.txt" -Value "apple"
Set-Content -Path "banana.txt" -Value "banana"
Set-Content -Path "notes.log" -Value "note"
(Get-ChildItem -Filter "*.txt" | Measure-Object).Count

Example

Set-Content -Path "report.txt" -Value "report"
Set-Content -Path "data.txt" -Value "data"
Set-Content -Path "old.log" -Value "old"
$names = Get-ChildItem -Filter "*.txt" | Sort-Object Name | Select-Object -ExpandProperty Name
$names -join ", "
"Count: " + $names.Count

Key points

  • Get-ChildItem: the cmdlet that lists the files in a folder.
  • Filter: the -Filter parameter keeps only names that match a pattern, such as *.txt.
  • Pipeline: the | operator passes the listed files from one cmdlet to the next.
  • Sort-Object: the cmdlet that puts results in order, such as by name.
  • Select-Object: the cmdlet that picks one property from each result, such as Name.

In this example, three files are created, then Get-ChildItem lists only the .txt files. Sort-Object puts them in name order, Select-Object keeps just the names, and the last two lines print the names joined on one line and then the count.

Note

always filter to the files you created and sort by name, because folder order is not guaranteed.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which command lists only the .txt files in a folder, in name order?