从多个 Zip 文件中提取特定文件类型到 Powershell 中的一个文件夹 [英] Extract Specific Filetypes From Multiple Zips to one Folder in Powershell
问题描述
我有几个包含多种文件类型的 zip 文件.我唯一感兴趣的是 .txt 文件.我只需要提取 .txt 文件并将它们放在自己的文件夹中,忽略 zip 文件中的所有其他文件类型.
I have Several zip files that Contain multiple filetypes. The ONLY ones I am interested in are the .txt files. I need to extract the .txt files only and place them in a folder of their own, ignoring all other file types in the zips files.
所有 zip 文件都在同一个文件夹中.
All the zip files are in the same folder.
示例
-foo.zip
--1.aaa
--2.bbb
--3.ccc
--4.txt
-foo2.zip
--5.aaa
--6.bbb
--7.ccc
--8.txt
我想将 4.txt
和 8.txt
提取到另一个文件夹.我一生都无法弄清楚,花了很多年的时间寻找、谷歌搜索和尝试.甚至设法偶尔删除到 zips :-)
I want to have 4.txt
and 8.txt
extracted to another folder. I can't for the life of my figure it out and spent ages looking, googling and trying. Even managing to delete to zips once in a while :-)
提前致谢
推荐答案
使用 ZipArchive
类型以在提取前以编程方式检查存档:
Use the ZipArchive
type to programmatically inspect the archive before extracting:
Add-Type -AssemblyName System.IO.Compression
$destination = "C:destinationfolder"
# Locate zip file
$zipFile = Get-Item C:path ofile.zip
# Open a read-only file stream
$zipFileStream = $zipFile.OpenRead()
# Instantiate ZipArchive
$zipArchive = [System.IO.Compression.ZipArchive]::new($zipFileStream)
# Iterate over all entries and pick the ones you like
foreach($entry in $zipArchive.Entries){
if($entry.Name -like '*.txt'){
# Create new file on disk, open writable stream
$targetFileStream = $(
New-Item -Path $destination -Name $entry.Name -ItemType File
).OpenWrite()
# Open stream to compressed file, copy to new file stream
$entryStream = $entry.Open()
$entryStream.BaseStream.CopyTo($targetFileStream)
# Clean up
$targetFileStream,$entryStream |ForEach-Object Dispose
}
}
# Clean up
$zipArchive,$zipFileStream |ForEach-Object Dispose
对每个 zip 文件重复.
Repeat for each zip file.
请注意,上面的代码具有非常少的错误处理,可以将其视为示例
Note that the code above has very minimal error-handling, and is to be read as an example
这篇关于从多个 Zip 文件中提取特定文件类型到 Powershell 中的一个文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!