从多个ZIP提取特定文件类型到Powershell中的一个文件夹 [英] Extract Specific Filetypes From Multiple Zips to one Folder in Powershell

查看:92
本文介绍了从多个ZIP提取特定文件类型到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文件都位于

示例

-foo.zip

--1.aaa
--2.bbb
--3.ccc
--4.txt

-foo2.zip

--5.aaa
--6.bbb
--7.ccc
--8.txt

我想拥有 4.txt 8.txt 提取到另一个文件夹。我一辈子都想不出来,花了很长时间寻找,搜寻和尝试。甚至设法偶尔删除zip:-)

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:\destination\folder"

# Locate zip file
$zipFile = Get-Item C:\path\to\file.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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆