3

I found one strange behaviour when I'm using Get-ChildItem cmdlet

Folder structure:

d:\test\fooA\foo\1-9.txt files
d:\test\fooB\foo\1-9.txt files
d:\test\fooC\foo\1-9.txt files
d:\test\fooD\foo\1-9.txt directories

When I use below syntax I will get all 1-9.txt files and directories from all recursed folders. It works as expected.

Get-ChildItem -Filter *.txt -Path D:\test\*\foo -Recurse

When I add parameter -Directories I get only directories from last folder in example. It works as expected too.

Get-ChildItem -Directory -Filter *.txt -Path D:\test\*\foo -Recurse

When I add parameter -File instead of -Directories I get nothing. I expected that I will get only files.

Get-ChildItem -File -Filter *.txt -Path D:\test\*\foo -Recurse

When I use parameter -File and -Directory I get nothing too.

Get-ChildItem -Directory -File -Filter *.txt -Path D:\test\*\foo -Recurse

I tested PowerShell version 5.1 and 7 on different windows systems. From my perspective it looks more like bug than issue in code or my understanding of usage this cmdlet, can someone double check and comment ? I can fix my issue by additional coding, but I do not understand why it works for folders but not for files.

Many thanks for any comment.

1 Answers1

5

This is a known bug with Powershell's FileSystem provider. Get-ChildItem uses this when specifying -File or -Name parameters. It will probably never be fixed due to risk of breaking existing stuff:

https://github.com/PowerShell/PowerShell/issues/9014

The recommended option is piping to Where-Object filters instead, like:

# Exclude directories
Get-ChildItem -Filter *.txt  -Path 'D:\test\*\foo' -Recurse | Where { -not $_.PSIsContainer }
Cpt.Whale
  • 10,914