How can I filter Read-Archive output?

Topics: User Forum
Aug 4, 2013 at 7:58 PM
Hello all,

I'm trying to extract some files from an archive. According to the help example, I should be doing this:
Read-Archive myarchive.tar | Where-Object { $_.Name -like "*.txt" } | Expand-Archive
In fact, Expand-Archive always extracts all files from the archive. I think this is because Read-Archive only writes out one object, which is a list of all files in the archive, and Where-Object either passes the whole list through (if there is a matching file) or not (if not).

I have found an ugly workaround:
$(foreach ($elem in (Read-Archive myarchive.tar)) { Write-Output $elem }) | Where-Object { $_Name -like "*.txt" } | Expand-Archive
This basically takes the one collection that comes out of Read-Archive and produces each individual element. It works, but I would not want to be caught having written it.

Is there a better way?
Aug 6, 2013 at 12:03 AM
Yes, there is:
(Read-Archive myarchive.tar).GetEnumerator() | Where-Object ...
That is at least usable. I still think Read-Archive should produce individual items instead of the whole list at once.
Developer
Aug 6, 2013 at 12:32 AM
Urgh... I don't how in the name of all that's holy that got by... you are indeed correct. Read-Archive should emit one item at a time; at one time, it did exactly that. I wonder if it's a powershell quirk. What version of PS are you using?
Aug 6, 2013 at 12:37 AM
PowerShell 3.

And now that I've asked for help, I think I also found the bug; it's even mentioned in the source. The last uncommented line of Pscx.Commands.IO.Compression.ReadArchiveCommand.ProcessArchive(FileInfo archive) has this to say:
WriteObject(entries, enumerateCollection: false); // true? which is better for piping to expand-archive?
Developer
Aug 6, 2013 at 1:20 AM
Weird... that should have been true, without a doubt. I don't understand why there is confusion there. Sigh...


Aug 6, 2013 at 1:37 AM
PowerShell is really something, sometimes.

Does not work:
Read-Archive myarchive.tar | Where-Object ...
Works:
(Read-Archive myarchive.tar) | Where-Object ...