Skip to main content

Extract only specified files from a zip archive in PowerShell.

# Ref:

function ExtractFromArchive([string] $Path, [string] $DestinationPath, [string] $Filter)
    # ensure the output folder exists
    $exists = Test-Path -Path $DestinationPath
    if ($exists -eq $false)
        $null = New-Item -Path $DestinationPath -ItemType Directory -Force

    # load ZIP methods
    Add-Type -AssemblyName System.IO.Compression.FileSystem

    # open ZIP archive for reading
    $zip = [System.IO.Compression.ZipFile]::OpenRead($Path)

    # find all files in ZIP that match the filter (i.e. file extension)
    $zip.Entries | Where-Object { $_.FullName -like $Filter } | ForEach-Object {
        # extract the selected items from the ZIP archive and copy them to the out folder
        $fileName = $_.Name
        $outFile = Join-Path -Path $DestinationPath -ChildPath $fileName
        [System.IO.Compression.ZipFileExtensions]::ExtractToFile($_, $outFile, $true)

    # close ZIP file

# Example
# Extract all *.txt files from to a folder called "text-files"

$SCRIPTDIR = Split-Path $script:MyInvocation.MyCommand.Path

$zipFile = Join-Path -Path $SCRIPTDIR -ChildPath ""
$outputDirectory = Join-Path -Path $SCRIPTDIR -ChildPath "text-files"
ExtractFromArchive -Path $zipFile -DestinationPath $outputDirectory -Filter "*.txt"