Andy
Andy

Reputation: 1423

How to use -Exclude to exclude all the contents of a specific folder in PowerShell?

Want to get all the contents of the tree folder, except for the L1 subfolder [^1].

which in the current case has two files, fill.txt and dbg.log.

Originally I wanted to use -Exclude, but after trying many usages I could not achieve.

# I don't know why the exclude parameter doesn't seem to work
Get-ChildItem -Recurse -Path 'tree' -Exclude 'tree\L1' | Should -Not -HaveCount 2
Get-ChildItem -Recurse -Path 'tree' -Exclude 'tree\L1\*' | Should -Not -HaveCount 2
Get-ChildItem -Recurse -Path 'tree' -Exclude "$('tree\L1'|Resolve-Path)*" | Should -Not -HaveCount 2

Where-Object works:

Get-ChildItem -Recurse -Path 'tree' | Where-Object {
    [string]$_ -notlike "$('tree\L1'|Resolve-Path)*"
} | Should -HaveCount 2

What's wrong with the way I use Exclude parameter? How to correct it?

supplement: That's just a case. I want to know how to use the -Exclude parameter to do this.

[^1]:

\tree
├──L1
│  ├──L2
│  │  ├──L3
│  │  │  ├──300.txt
│  │  │  └──xtf.log
│  │  ├──L3_1
│  │  │  ├──123.fp
│  │  │  └──dbg.log
│  │  ├──300.txt
│  │  └──xtf.log
│  ├──L2_1
│  │  ├──150.txt
│  │  └──15x.txt
│  ├──L2_2
│  │  ├──dbg_2.log
│  │  └──dbg.log
│  └──tl.txt
├──dbg.log
└──fill.txt

Upvotes: 1

Views: 347

Answers (1)

KUTlime
KUTlime

Reputation: 8157

As already mentioned in the comments, you wan something which is not achievable by using the -Exclude parameter.

This parameter operates only with item names. Unfortunately, this gotcha is not well documented by the official documentation.

Upvotes: 1

Related Questions