38

I'm trying to get child items of a folder recursively. However the folder contains noise files and folder (actually, this is a Visual Studio project folder).

Here what I have:

$root = Get-Item C:\Projects\MyProject

$allItems =  Get-ChildItem $root -Recurse -exclude "**\pkgobj\*"

However, $allItems still contains files and folder matching the paths.

What I did wrong?

To be more precise, I want to get both folders and files, but not the specified folder, and any of its descendant.

I also tried:

foreach($item in $allItems){
    if($item.FullName -notmatch "pkgobj") {
        Write-Host -ForegroundColor Green $item.FullName.Replace($root,'')

    }
}

But no more success

2 Answers 2

61

Took me a moment to understand the issue. Its a tricky one.

-exclude only applies to basenames of items (i.e. myfile.txt), not the fullname
(i.e. C:\pkgobj\myfile.txt) which you want. So you can't use exclude here.

But there is a workaround using Fullname and -notlike

$root = "C:\Projects\MyProject"
$allitems = Get-ChildItem $root -Recurse | Where {$_.FullName -notlike "*\pkgobj\*"} 
2
  • 3
    However, if you want to exclude large directories due to performance (like node_modules), this won't help since it will still recursively check everything and filter afterwards.
    – Pluc
    Feb 26, 2019 at 15:50
  • What about this ? Get-ChildItem -Exclude exclude_dir | foreach { Get-ChildItem -Path $_ -Include *.include -Recurse -Exclude *.excludefile | foreach { echo $_ } }
    – NN_
    May 20, 2019 at 18:18
1

You want to avoid where statements when you can for performance reasons. To simplify a previous answer.

Get-childitem -path c:\windows -exclude 'temp' | get-childitem -recurse
1
  • 4
    Thanks... but don't your query applies to top level folders only ? What about if there's a folder name `c:\windows\foo\temp` ?
    – Steve B
    Jul 27, 2020 at 8:18

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .