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

up vote 32 down vote accepted

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\*"} 

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.