1

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.

Martim Passos
  • 137
  • 1
  • 12

1 Answers1

1

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.

mklement0
  • 382,024
  • 64
  • 607
  • 775
  • Thank you for clarifying this. Do you happen to spot any inconsistency in my ```Test-Path``` usage? It is still overwriting all files at destination... Does ```BaseName``` work only with full path objects? – Martim Passos Sep 17 '20 at 22:34
  • 1
    @MartimPassos: Try `"./jpeg/$($_.Basename).jpg"` - see https://stackoverflow.com/a/40445998/45375 and https://stackoverflow.com/a/41254359/45375 – mklement0 Sep 17 '20 at 22:57