Powershell – Extract Files from ZIP Archive


To totally unlock this section you need to Log-in

Starting with PowerShell 5, cmdlets like Expand-Archive can extract the content of ZIP files to disk. However, you can always extract only the entire archive.

If you’d rather like to extract individual files, you can resort to .NET methods. Here is a sample that does this:

Comments in the code explain what the code does. Just make sure you adjust the initial variables and specify a ZIP file that exists, and a file extension that exists inside the ZIP file:

# Requires -Version 5.0
# Change $Path to a ZIP file that exists on your system!
$Path = "$Home\Desktop\Test.zip"

# Change extension filter to a file extension that exists
# Inside your ZIP file
$Filter = '*.sql'

# Change output path to a folder where you want the extracted
# Files to appear
$OutPath = 'C:\ZIPFiles'

# Ensure the output folder exists
$exists = Test-Path -Path $OutPath
if ($exists -eq $false)
{
  $null = New-Item -Path $OutPath -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
    [System.IO.Compression.ZipFileExtensions]::ExtractToFile($_, "$OutPath\$FileName", $true)
    }

# Close ZIP file
$zip.Dispose()

# Open out folder
explorer $OutPath

Expand-Archive

The above method let use to filter which type of files we want to extract from a .zip archive (in the above example *.sql files). Unfortunately, the Expand-Archive cmdlet (available by default in Powershell without calling a .NET namespace), in contrast, does not have this possibily, as shown below (see more at https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.archive/expand-archive?view=powershell-7.1):

Expand-Archive -LiteralPath <PathToZipFile> -DestinationPath <PathToDestination>

The destination folder specified to extract the files into will populate with the contents of the archive. If the folder didn’t exist before unzipping, PowerShell will create the folder and place the contents into it before unzipping.

By default, if you leave out the -DestinationPath parameter, PowerShell will unzip the contents into the current root directory and use the name of the Zip file to create a new folder.

If the folder already exists in the destination, PowerShell will return an error when it tries to unzip the files. However, you can force PowerShell to overwrite the data with the new ones using the -Force parameter.

You should only use the -Force parameter if the old files are no longer needed, as this will irreversibly replace the files on your computer.

Expand-Archive cmdlet has the following parameters/options available:

  • Path - specifies the path to the compressed archive file (zip) that we want to extract. It is a positional parameter with position 0.
  • DestinationPath - specifies the path to the folder where we want to extract. It is a parameter on position 1.
  • LiteralPath - It is very similar to the Path parameter but the only difference is that it doesn’t interpret any character in the path as a wildcard.
  • Force - runs without asking for user confirmation.
  • PassThru - Causes the cmdlet to output a list of files expended from the compressed archive.
  • WhatIf - Shows what would happen if the command runs.
  • Confirm - Prompt confirmation before execution.

NOTE: You can pipe a string that contains a path to an existing archive file.

The general syntax of the Expand-Archive is the following:

Expand-Archive [[-DestinationPath] ] [-Confirm] [-Force] -LiteralPath*  [-WhatIf][<CommonParameters>]
Expand-Archive [-Path*]  [[-DestinationPath] ] [-Confirm] [-Force] [-WhatIf] [<CommonParameters>]

NOTE: This cmdlet supports the <CommonParameters>: Verbose, Debug,ErrorAction, ErrorVariable, WarningAction, WarningVariable,OutBuffer, PipelineVariable, and OutVariable.

$shell.NameSpace

An alternative method to the Expand-Archive default cmdlet, with a basic "filtering" method that will let us to specify a single file to extract (in this example), is the following function (ExtractFilesFromZip), that will use the shell.application COM object directly in Powershell to be able to interact with the archiving feature of Windows Explorer.

NOTE: ComObject, or plain COM, is a key PowerShell command that performs many of the jobs previously undertaken by VBScript.

function ExtractFilesFromZip($zipsource, $filename, $dest) { 
 
    $FOF_SILENT_FLAG = 4 
    $FOF_NOCONFIRMATION_FLAG = 16 
 
        foreach($item in $zipsource.items()) { 
                If ($item.Name -eq $filename) { 
                        $shell.NameSpace($path).copyhere($item, $FOF_SILENT_FLAG + $FOF_NOCONFIRMATION_FLAG) 
                } 
                else {
                        # you can add something for logging or debugging
                 } 
        } 
} 
 
#connect shell.application to work with zipped content
$shell = new-object -com shell.application 
 
#path where zip-archive is
$path = "C:\DataFolder\Work\"
 
#filename of archive
$zip_file = "eas_ch03.zip" 
 
#name of file for extracting 
$file_to_extract = "eas029.csv" 
 
#read zip content 
$zip = $shell.NameSpace($path + $zip_file) 
 
#execute function
ExtractFilesFromZip -zipsource $zip -filename $file_to_extract -dest $path

System.IO.Compression.ZipFile

Finally, we can use, as another alternative (this time to extract all the contents from the ZIP archive, without any filter), the following approach, using this time the System.IO.Compression.ZipFile class (always from the System.IO.Compression .NET namespace) and the ExtractToDirectory method:

Add-Type -Assembly "System.IO.Compression.Filesystem"
[System.IO.Compression.ZipFile]::ExtractToDirectory('C:\Data\Compressed.zip','C:\Data\two')

7Zip4Powershell Module

7Zip4Powershell is PowerShell Module developed by Thomas Freudenberg and used for creating and extracting 7-Zip archives. If you have not already installed this module than the first thing to do is to install this module with the command:

Install-Module -Name 7Zip4PowershellCopy

IMPORTANT: You need to run PowerShell Console as an Administrator in order to successfully install this module!

After installing the module we can quickly investigate commands that come with this Module:

Get-Command -Module 7Zip4Powershell

We will use Expand-7Zip CmdLet from 7Zip4Powershell Module to extract our files or folders. Here is one simple example call to Expand-7Zip CmdLet in order to extract files from compressed archive:

Expand-7Zip -ArchiveFileName "C:\Temp\Zip\FilesZipped.zip" -TargetPath "C:\Temp\UnZip"

The following is the syntax related to the Expand-7Zip:

Expand-7Zip
    [-ArchiveFileName] 
    [-TargetPath] 
    [-Password ] | [-SecurePassword ]
    [<CommonParameters>]

The GitHub repository and the link to the Powershell Gallery page are the following:


Summary
Article Name
Powershell - Extract Files from ZIP Archive
Description
Starting with PowerShell 5, cmdlets like Expand-Archive can extract the content of ZIP files to disk. However, you can always extract only the entire archive. Luckily, there are other methods to extract, not only, from .zip archives, specified files or folders, on Windows-based systems.
Author
Publisher Name
Heelpbook.net