Ambiguous behavior by Get-ChildItem cmdlet in Powershell

119 Views Asked by At

I'm trying to get a list of all txt files in a local folder.

$dir = "C:\report\"
Get-ChildItem -Path $dir -File -Include "*.txt"

Above code returns nothing, However when I add wildcard * in front of the path, the command works as expected and returns the list of txt files.

$dir = "C:\report\*"
Get-ChildItem -Path $dir -File -Include "*.txt"

Without the -Include "*.txt" parameter, I get list of all files in both the cases (System.IO.FileInfo object)

I'm wondering why adding -Include "*.txt" is causing this ambiguous behavior? I'm new to PowerShell and I'm using Powershell 7. Thanks in advance.

1

There are 1 best solutions below

0
On BEST ANSWER

The Include parameter works when combined with theRecurse switch, OR as you have noticed by appending \* to the path, which implies recursion.

If you do not want the cmdlet to recurse through subfolders, use -Filter '*.txt' instead.