[PowerShell] How to list files or folders in a path
While Test-path cmdlet validates if a file or folder exists, Get-ChildItem cmdlet lists files or folders in the current path. This cmdlet is very useful when a PowerShell script is run to perform certain tasks.
Below is a basic example of Get-ChildItem cmdlet usage.
Scenario 1:
Given that I have copied a file to a destination path
When I check if the file exists
Then I could see a list of files or folders including the file that I just copied
Example of code:
$customerList = "C:\PowerShellExercise\CustomerList"
Get-ChildItem -path $customerList
There are a few parameters that I always used together with Get-ChildItem cmdlet.
Parameter | Description |
---|---|
-Filter | To list based on the filtered value |
Example: | |
-Filter “CustomerListA.txt” | |
-Filter “CustomerList* | |
Note: Add “*” at the front or/and end of the value for matching specific pattern. | |
-Include | It is similar like -Filter parameter but “*” need to be added at the path value and/or include value to display the list of the files/folders. |
-Exclude | It gives the opposite result of -Filter and -Include. It will list all the files/folder except the value defined. |
-Recurse | It will display all the files and folders and their children. |
-Name | It will list all the files by the name only. |
Example of code:
Get-ChildItem -path $customerList -Filter "CustomerListA.txt"
Get-ChildItem -path $customerList -Name "CustomerListA*"