简体   繁体   中英

Strange Powershell GCI Recurse Results with Wildcard

I'm trying to use GCI with the Recurse argument to get a list of all files WITHIN the subfolders of a specified path.

I'm using the following line:

gci 'C:\temp\TestRecurse\*\*' -Recurse

Underneath the TestRecurse folder, I have the following:

TestRecurse
 |---b.txt
 |---dir1
 |------a.txt

I expect a.txt to be returned. However, I'm getting a.txt and b.txt. Stranger still to me, if I put a.txt into another subfolder:

TestRecurse
 |---b.txt
 |---dir1
 |------dir2
 |---------a.txt

The same statement above only returns a.txt. I'm baffled as to how messing with the location of a.txt changes when b.txt is returned. Can someone explain to me why this happens, and why b.txt is ever returned at all?

Update

I should mention, while they're appreciated, I'm not necessarily looking for a workaround. This is part of a larger script in our environment that is in charge of moving files around in various ways while trying stay flexible. It's not behaving as I expected it would, so I'm trying to understand why it's working the way it is. As pointed out by PetSerAl, understanding Get-ChildItem may be more trouble than it's worth.

Thanks!

You're including a wildcard for the parent directory ( TestRecurse\\* ), so you are getting files contained in it as well. Try getting the folder list of the TestRecurse , then iterating through them.

Structure:

TestRecurse\b.txt
TestRecurse\dir1
TestRecurse\dir1\a.txt

Code:

Get-ChildItem 'C:\tmp\TestRecurse\' | `    # Get the list of items within TestRecurse
   ? {$_.PSIsContainer} | `                # Filter items that are folders
   % {Get-ChildItem $_.FullName -Recurse}  # Iterate through and get all items within those folders

This only returns folders and files within dir1, but not dir1 itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM