且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

从多个ZIP提取特定文件类型到Powershell中的一个文件夹

更新时间:2023-02-08 18:18:47

使用 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