How to Use Get-ChildItem in PowerShell: Syntax and Examples
Use the
Get-ChildItem cmdlet in PowerShell to list files and directories in a specified location. You can specify a path and use parameters like -Recurse to include subfolders or -Filter to narrow results.Syntax
The basic syntax of Get-ChildItem is:
Get-ChildItem [-Path] <string>: Specifies the folder to list.-Recurse: Lists items in all subfolders.-Filter <string>: Filters items by name or pattern.-File: Shows only files.-Directory: Shows only directories.
powershell
Get-ChildItem [-Path] <string> [-Recurse] [-Filter <string>] [-File] [-Directory]
Example
This example lists all files and folders in the current directory and its subdirectories, showing only files with the .txt extension.
powershell
Get-ChildItem -Path . -Recurse -Filter *.txt -File
Output
Directory: C:\Users\User\Documents
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a---- 2024-06-01 10:00 1234 notes.txt
-a---- 2024-06-02 11:15 5678 todo.txt
Common Pitfalls
One common mistake is forgetting to use -Recurse when you want to list files in subfolders. Another is using -Filter incorrectly; it only accepts simple wildcard patterns, not full regular expressions. Also, mixing -File and -Directory without understanding their effect can lead to empty results.
powershell
Get-ChildItem -Path C:\Folder -Filter *.txt # This lists only files and folders in C:\Folder, not subfolders. Get-ChildItem -Path C:\Folder -Recurse -Filter *.txt # Correct: includes subfolders. Get-ChildItem -Path C:\Folder -Filter "^.*\.txt$" # Incorrect: -Filter does not support regex, so no results. Get-ChildItem -Path C:\Folder -File -Directory # Incorrect: these parameters cannot be combined; results will be empty.
Quick Reference
| Parameter | Description |
|---|---|
| -Path | Specifies the folder or drive to list items from. |
| -Recurse | Includes all items in subfolders recursively. |
| -Filter | Filters items by simple wildcard pattern (e.g., *.txt). |
| -File | Shows only files, excluding folders. |
| -Directory | Shows only directories, excluding files. |
Key Takeaways
Use Get-ChildItem to list files and folders in a directory.
Add -Recurse to include all subfolders in the listing.
Use -Filter with simple wildcards to narrow down results.
Use -File or -Directory to show only files or folders respectively.
Avoid combining incompatible parameters like -File and -Directory together.