Extract Specific Filetypes From Multiple Zips to one Folder in Powershell

前端 未结 3 1573
被撕碎了的回忆
被撕碎了的回忆 2020-12-12 02:20

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 fold

3条回答
  •  一整个雨季
    2020-12-12 02:29

    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
    

    Repeat for each zip file.

    Note that the code above has very minimal error-handling, and is to be read as an example

提交回复
热议问题