且构网

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

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

更新时间:2023-02-08 18:40:37

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