To get files only but not folders using the Get-ChildItem cmdlet, you can use the -File parameter.
The following methods show how you can do it with syntax.
Method 1: Get files only using Get-ChildItem
Get-ChildItem -File
This example will return only files in the current directory.
Method 2: Get files with extension using Get-ChildItem
Get-ChildItem -File -Filter "*.txt"
This example will return only files with .txt extension from the current directory.
The following examples show how you can use these methods.
How to Get Files Only Using Get-ChildItem cmdlet in PowerShell
To get files only not the folders with the Get-ChildItem cmdlet, use the -File parameter.
# specify the directory path $folderPath = "C:\temp\log" # get files only $files = Get-ChildItem -Path $folderPath -File -Recurse Write-Output $files
Output:
In this script, we defined a variable $folderPath that contains the directory path from where we wanted to retrieve only files but not folders.
The Get-ChildItem cmdlet in PowerShell uses the -Path parameter to specify the $folderPath and the -File parameter to retrieve only files from the specified directly and store the result in the $files variable.
Finally, we use the Write-Output cmdlet to output the retrieved files from the directory.
How to Get Files with Extension Using Get-ChildItem in PowerShell
To get files with extension using the Get-ChildItem cmdlet in PowerShell, you can use the -File and -Filter parameters to specify the criteria to retrieve files.
# specify the directory path $folderPath = "C:\temp\log" # get files only $files = Get-ChildItem -Path $folderPath -File -Recurse -Filter "*.txt" Write-Output $files
Output:
In the script, the Get-ChildItem cmdlet uses the -File and -Recurse parameters to recursively get all files from the specified $folderPath and the -Filter parameter to specify the criteria to return only .txt extension files only.
Finally, the Write-Output cmdlet outputs the files with an extension from the directory.
Conclusion
I hope the above article on getting only files using the Get-ChildItem cmdlet in PowerShell is helpful to you.
You can find more topics about Active Directory tools and PowerShell basics on the ActiveDirectoryTools home page.