Martim Passos
Martim Passos

Reputation: 317

Getting -Filter or -Include values from .txt file

I have a txt file with filenames (i.e 01234.tif) that I would like to use to filter a Get-ChildItem cmdlet. I did

$filenames = Get-Content filenames.txt

(also tried with | Out-String)

and then

Get-ChildItem . -Include $filenames | ForEach {if (!(Test-Path -Path ./jpeg/$_.Basename+".jpg")) {some imagemagick processing}}

but it does nothing. Funny part is that it works for excluding, since

Get-ChildItem . -Exclude $filenames > exclude.txt

writes the expected amount of lines. What am I missing here?

Get-Content filenames.txt | ForEach (path test) {imagemagick}

runs but copies all items, so either the path checking or Get-Content isn't working as expected.

Upvotes: 1

Views: 412

Answers (1)

mklement0
mklement0

Reputation: 437773

Perhaps surprisingly, -Include (also -Exclude) is first applied to the names of the (possibly wildcard-expanded) input path(s), and - only in case of match - then to the children of directories targeted by literal path(s).
The problem does not arise if -Recurse is also used.
See GitHub issue #3304.

Therefore, use Get-Item * (Get-ChildItem * would work too, but only with -Include, not (properly) with -Exclude), so that the names of the child items are matched against the -Include patterns:

Get-Item * -Include (Get-Content filenames.txt)

Add -Force to also include hidden items.

See this answer for a detailed discussion of the pitfalls of -Include and -Exclude.

Upvotes: 1

Related Questions