Powershell найти и добавлять файлы в zip, соответствуя имя файла и имя его родительской папки

powershell extract zip

Fortunately, PowerShell provides a comprehensive set of commands that can help you automate this process and make it more efficient. In this guide, we’ll take a closer look at how to use PowerShell to extract files from archives.

PowerShell has had the ability to both create and extract contents from ZIP files for quite some time. Even so, PowerShell’s native support for handling ZIP files is somewhat limited. Fortunately, we have a workaround to overcome these limitations.

Introduction to PowerShell Unzip

PowerShell is a powerful scripting language that allows you to automate many different tasks, including file extraction and compression. With PowerShell, you can easily extract files from compressed archives, as well as create your own compressed files. PowerShell uses a set of cmdlets (pronounced “command-lets”) to perform these operations. A cmdlet is a lightweight command that performs a specific action. In the case of file extraction and compression, PowerShell provides Expand-Archive and Compress-Archive cmdlets that you can use to automate these tasks.

As you can see, the Compress-Archive and Expand-Archive cmdlets are simple to use. Nevertheless, they come with certain limitations.

Firstly, native cmdlets use UTF-8 encoding. If you open a ZIP file created by another utility that uses a different encoding, the filenames may be incorrect.

Secondly, there is a size cap of 2 GB for compressed archives. The Compress-Archive cmdlet also ignores hidden files and folders.

However, the most notable constraint is the absence of . As a result, you cannot create or access a password-protected ZIP using Compress-Archive and Expand-Archive cmdlets.


Sean O’Shea, RCA, CEDS, CeDP


Sean O’Shea, RCA, CEDS, CeDP

Legal Assistant at Patterson Belknap Webb & Tyler LLP

Create a text file with each line beginning with Expand-Archive -LiteralPath ‘

Expand-Archive -LiteralPath “C:\foofolder\” -DestinationPath “C:\foofolder\extracthere”

Expand-Archive -LiteralPath “C:\foofolder\Litigation Support.7z” -DestinationPath “C:\foofolder\extracthere”

Open Windows PowerShell ISE (x86), and paste this script into the script pane.

Note that this method will not work for 7zip files.

I tested this tonight and successfully extracted more than 50,000 files from almost 50 zip files.

Help improve contributions

Contribution hidden for you

  • To zip (compress) files, open PowerShell (admin) and run the Compress-Archive -Path C:\SOURCE\FILES\* -CompressionLevel Optimal -DestinationPath C:\DESTINATION\ZIPPEDFILE.zip command.
  • To unzip (extract) files, open PowerShell (admin) and run the Expand-Archive -Path C:\SOURCE\ZIPPED.zip -DestinationPath C:\DESTINATION\UNZIP command.
  • You can also use PowerShell to add more files to the archival format or change the compression ratio.

On Windows 10 (or 11), you can use a zip file to package and compress files and folders for easier sharing or to store files that you don’t use frequently.

Although you can use File Explorer to quickly create a zip file or extract the contents of a zipped file, you can also use PowerShell to perform the same tasks more efficiently with commands. In addition, you can even select the compression ratio to zip files even faster or optimize to save space.

In this guide, I will teach you how to zip and unzip files and folders using PowerShell commands on Windows 10. Although these instructions are focused on Windows 10, they also apply to systems running Windows 11.

To zip files with PowerShell on Windows 10 (or 11), use these steps:

  1. Open Start on Windows.

  2. Compress-Archive -Path C:\SOURCE\PATH\TO\YOUR\FILES\* -CompressionLevel Optimal -DestinationPath C:\DESTINATION\PATH\ZIPPEDFILE.zip

    Zip files using PowerShell

    In the command, change the source and destination to match your specific paths. The wildcard “*” tells the command to compress the source folder’s contents.

Once you complete the steps, PowerShell will compress the folder and all its content, creating a new .zip file with a compressed version of the files.

I’m trying to zip using PowerShell but it’s not excluding the files listed in the excluded_paths. I want to especially exclude all __pycache__ folder occurrences that can be nested in different levels of my python code base. Currently everything gets zipped including the files and folders that are supposed to be excluded.

$excluded_paths = @(
    "${parent_folder}/.vscode/*",
    "${parent_folder}/.git/*",
    "${parent_folder}/temp/*",
    "${parent_folder}/resources/documentation/*",
    "${parent_folder}/**/useful/*",
    "${parent_folder}/scripts/*",
    "${parent_folder}/*.template.*",
    "${parent_folder}/*TODO.*",
    "${parent_folder}/$(Get-Item -Path $MyInvocation.MyCommand.Path).Name"
)

$exclude_pycache = Get-ChildItem -Path $parent_folder -Recurse -Directory -Filter "__pycache__" | ForEach-Object { $_.FullName }

$excluded_paths += $exclude_pycache

Pause

$winrar_path = "C:\Program Files\WinRAR\WinRAR.exe"

#$exclusion_switches = $excluded_paths | ForEach-Object { "-x'$_'" }
#& $winrar_path a -r -ep1 $exclusion_switches "$output_zip" "${parent_folder}\*"

$exclusion_string = $excluded_paths -join ' '
& $winrar_path a -r -ep1 "-x$exclusion_string" "$output_zip" "${parent_folder}\*"

I tried this:

$exclusion_switches = $excluded_paths | ForEach-Object { "-x'$_'" }
& $winrar_path a -r -ep1 $exclusion_switches "$output_zip" "${parent_folder}\*"

and tried this one:

$exclusion_string = $excluded_paths -join ' '
& $winrar_path a -r -ep1 "-x$exclusion_string" "$output_zip" "${parent_folder}\*"

Even a simple example:

& $winrar_path a -r -x__pycache__ "$output_zip" "${parent_folder}\*"

does not work. It zips but it does not exclude all the __pycache__ folders.

Ok I tried

& $winrar_path a -r "-x*__pycache__*" "$output_zip" "${parent_folder}\*"

and that worked but the WinRAR documentation did not mention to quote it.

What am I doing wrong?

Need powershell script for the below:

provided comma-separated filenames with parent folder like below:

$itemsToInclude = "stage\arsw.war,dev\deployfile"

I wish to search recursively for all comma-separated files mentioned in $itemsToInclude under the $workspace=”D:\ims” location

and include only the files where BOTH the filename and the parent folder-name matches into hello.zip

Thus D:\ims\work1\app1\src\stage\arsw.war should be included in hello.zip while D:\ims\work1\app1\src\wow\arsw.war should not because the parent folder should be stage as mentioned in the $itemsToInclude

D:\ims\work1\myapp2\src\dev\deployfile\file1.txt
D:\ims\work1\myapp2\src\dev\deployfile\file2.txt
D:\ims\work1\app1\src\stage\arsw.war

Tried the below powershell but it failed:

PS D:\ims> cd D:\ims

$workspace = “D:\ims” 
$itemsToInclude = “stage\arsw.war,dev\deployfile”

$items = $itemsToInclude -split “,” | ForEach-Object { $_.Trim() }

$matchingFiles = @()
foreach ($item in $items) { 
# Get the file name and the parent folder name from the item 

Write-Host "Split-Path -Path $item -Leaf"

$fileName = Split-Path -Path $item -Leaf

Write-Host "Split-Path -Path $item -Parent"

$parentFolder = Split-Path -Path $item -Parent

Write-Host "$fileName and $parentFolder"

$files = Get-ChildItem -Path $workspace -Filter $fileName -Recurse -File -ErrorAction SilentlyContinue | Where-Object { $_.Directory.Name -eq $parentFolder }


# Add the matching files to the array using array subexpression operator
$matchingFiles = @($matchingFiles; $files)

Write-Host "FOUND $($files.FullName) and $($matchingFiles.FullName)"

if ($matchingFiles) {
Compress-Archive -Path $matchingFiles -DestinationPath hello.zip 
} 
else { 

Write-Host “No matching files were found in $workspace” }

}
Split-Path -Path stage\arsw.war -Leaf
Split-Path -Path stage\arsw.war -Parent
arsw.war and stage
FOUND D:\ims\work1\app1\src\stage\arsw.war and D:\ims\work1\app1\src\stage\arsw.war
Compress-Archive : The path 'arsw.war' either does not exist or is not a valid file system path.
At line:33 char:1
+ Compress-Archive -Path $matchingFiles -DestinationPath hello.zip
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (arsw.war:String) [Compress-Archive], InvalidOperationException
    + FullyQualifiedErrorId : ArchiveCmdletPathNotFound,Compress-Archive
 
Split-Path -Path dev\deployfile -Leaf
Split-Path -Path dev\deployfile -Parent
deployfile and dev
FOUND  and D:\ims\work1\app1\src\stage\arsw.war
Compress-Archive : The path 'arsw.war' either does not exist or is not a valid file system path.
At line:33 char:1
+ Compress-Archive -Path $matchingFiles -DestinationPath hello.zip
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (arsw.war:String) [Compress-Archive], InvalidOperationException
    + FullyQualifiedErrorId : ArchiveCmdletPathNotFound,Compress-Archive

There are a couple of issues with this attempt.

  1. Files inside dev\deployfile is not Found although it is present.

  2. The files under dev\deployfile are not added to hello.zip

:/>  Программа для создания установочного диска Windows 7

Zip and Unzip files using PowerShell in Windows

Using PowerShell to zip or unzip files requires some technical knowledge, but it doesn’t necessarily require advanced knowledge. PowerShell commands are quite straightforward, particularly for basic operations such as zipping and unzipping files.

To create Zip files you begin by compressing some files into a ZIP file archive using the Compress-Archive cmdlet. It takes the path to any files you want to compress—multiple files are separated with a comma—and archives them in the destination you specify.

Zip files using PowerShell

Next, type in the syntax below, replacing <PathToFiles> and <PathToDestination> placeholder with the path to the files you want to compress and the name and folder you want it to go, respectively.

Compress-Archive -LiteralPath <PathToFiles> -DestinationPath <PathToDestination>

Compress-Archive cmdlet in PowerShell

Note: When you provide the destination path, be sure to give the archive file a name or PowerShell will save it as “.zip” where you specify. Also, bear in mind that quotations around the path are only necessary when the file path contains a space.

Alternatively, to zip the entire contents of a folder and all of its subfolders, you can use the same syntax as above, replacing <PathToFiles> and <PathToDestination> placeholder with the path to the files you want to compress and the name and folder you want it to go, respectively.

It should look like as shown in the image below.

Compressing contents of a folder and all of its subfolders

This command puts the path to a directory with multiple files and folders in it without specifying individual files. PowerShell takes everything inside of the root directory and compresses it, subfolders, and all.

Read: How to open .TAR.GZ, .TGZ or .GZ. Files.

The wildcard character (*) function

The Compress-Archive cmdlet lets you use a wildcard character (*) to expand the functionality even further. When you use the character, you can exclude the root directory, compress only files in a directory, or choose all files of a specific type. To use a wildcard with Compress-Archive, you must use the -Path parameter instead, as -LiteralPath does not accept them.

Now, from both examples given above, you have seen how to include the root directory and all of its files and subdirectories when creating an archive file. However, if you want to exclude the root folder from the Zip file, you can use a wildcard to omit it from the archive. By adding an asterisk (*) to the end of the file path, PowerShell will only grab what’s inside of the root directory. The correct syntax is presented below.

Compress-Archive -Path C:\path\to\file\* -DestinationPath C:\path\to\archive.zip

Use of wildcard character in PowerShell to zip file

Now, in the case whereby you have a folder with a bunch of different file types (.docx, .txt, .jpg, etc.) but only want to compress all of one type, you can use the syntax below. PowerShell will archive the files specified without touching the others explicitly. Bear in mind that subdirectories and the files of the root folder aren’t included in the archive with this method.

Compress-Archive -Path C:\path\to\file\*.docx -DestinationPath C:\path\to\archive.zip

Zipping files of same type using PowerShell

Zip files of same type - output

Lastly, if you want an archive that only compresses files in the root directory and leaves all its subdirectories, you will use the star-dot-star (*.*) wildcard to zip the files with the syntax below. With this method too, the root directory’s subdirectories and the root directory aren’t included in the archive.

Compress-Archive -Path C:\path\to\file\*.* -DestinationPath C:\path\to\archive.zip

Excluding subdirectories from zip in PowerShell

Now, it’s imperative to point out that even after the archive is complete, you can update an existing zipped file with the use of the -Update parameter with the correct syntax provided below. This lets you replace older file versions in the archive with newer ones that have the same names, and add files that have been created in the root directory.

Compress-Archive -Path C:\path\to\files -Update -DestinationPath C:\path\to\archive.zip

Updating destination zip folder using PowerShell

And this concludes the process of the various scenarios that you can zip files using PowerShell in Windows 11/10. Continue below to see how you can unzip files using PowerShell.

Unzip files using PowerShell

As you have already seen, PowerShell can be used to zip files. The utility also can unzip archives. The process is even easier than compressing them – all you need is the source file and a destination for the data ready to unzip.

Let’s get to it.

Next, type in the syntax below, replacing <PathToZipFile> and <PathToDestination> placeholder with the path to the files you want to compress and the name and folder you want it to go, respectively.

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

Unzip a Zip file using PowerShell

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.

Content of zip file extracted

Note that, if the folder Docs 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.

And this wraps up our subject on how to zip and unzip files using the PowerShell utility in Windows 11/10!

How do you zip and unzip files in Windows?

To zip or unzip files in Windows, you may use the built-in functionality of File Explorer, PowerShell, or any third-party file compression software, such as WinZip or 7-Zip. To zip files using Windows File Explorer, navigate to the location of the files you want to zip. Select the files, right-click on them, and select the Compress to ZIP file option. To unzip files, navigate to the zip archive in File Explorer, right-click on it, and select Extract All. Select a destination folder and click Extract to confirm your action.

How do I unzip a zip file in Windows command prompt?

Read Next: How to install CURL on Windows 11.

An Alternative Solution

The best workaround I have found involves using the 7-Zip PowerShell module. For those unfamiliar, 7-Zip is a freely available open-source tool for creating and extracting archive files. The named 7Zip4PowerShell enables you to access 7-Zip functionality directly from the command line.

Here is the command used to install the 7-Zip PowerShell module:

Install-Module -Name 7Zip4PowerShell

You can see what the installation process looks like in Figure 3.

:/>  Ключи для excel 2013 лицензионные на 2022-2023 год

A PowerShell screenshot showing the installation of the 7Zip4PowerShell module

Figure 3. This is how you install the 7Zip4PowerShell module.

Creating a ZIP archive using 7Zip4PowerShell is just as easy as it is with native PowerShell. The cmdlet you use is Compress-7Zip.

By the way, if you are curious about the list of the cmdlets included in the 7Zip4PowerShell module, you can use this command:

Get-Command -Module 7Zip4PowerShell

A PowerShell screenshot demonstrates the Get-Command and Get-Help cmdlets

Figure 4. You can use the Get-Command and Get-Help cmdlets to familiarize yourself with the 7Zip4PowerShell module’s cmdlets.

At any rate, if you wanted to create a ZIP file called C:\Scripts\Temp\Text.zip containing all the text files located in the C:\Scripts folder, you would use this command:

A PowerShell screenshot demonstrating the creation of a ZIP file

Figure 5. This is how you create a compressed archive using 7-Zip.

The Compress-7Zip cmdlet does indeed support a path parameter to specify what you want to include in the archive. In all honesty, though, I encountered some difficulties in getting the cmdlet to do what I wanted (it’s been a long day, maybe I’m just tired). So, I devised a workaround using the Get-ChildItem cmdlet to compile a list of files to include in the archive, which I then passed to the Compress-7Zip cmdlet via a pipeline operation. I used the -ArchiveFileName and the -Format parameters with the Compress-7Zip cmdlet. Technically, the -Format parameter isn’t required, but I included it to illustrate that 7-Zip supports various archive types beyond ZIP files.

Expand-7Zip -ArchiveFileName C:\Scripts\Temp\Text.zip -TargetPath C:\Scripts\Extract -Password ‘ABC’

You can this in action in Figure 6.

A PowerShell screenshot demonstrates the creation and accessing of a password-protected archive

Figure 6. This is how you create and open a password-protected archive.

Troubleshooting Common Issues with PowerShell Unzip

While PowerShell unzip operations are generally straightforward, you may encounter some common issues. Here are a few troubleshooting tips to help you overcome these challenges:

  • Verify that the ZIP file path and the destination folder path are correct and accessible.
  • Check if the ZIP file is not corrupted or encrypted with a password that requires additional steps for extraction.
  • Ensure you have the necessary permissions to extract files from the ZIP archive and write them in the destination folder.
  • Update your PowerShell version and modules to the latest versions to benefit from bug fixes and improvements that may resolve any known issues.

Understanding the PowerShell unzip command Expand-Archive

PowerShell unzip refers to the process of extracting files and folders from a ZIP archive using PowerShell commands. The Expand-Archive cmdlet is used to extract files from a compressed archive. To use the PowerShell unzip command, you’ll need to know the path and name of the compressed archive you want to extract files from. You’ll also need to specify the path to which you want to extract the files.

The Expand-Archive cmdlet is a built-in PowerShell command that allows you to extract files from a ZIP archive. This cmdlet is part of Microsoft.PowerShell.Archive module. The Expand-Archive cmdlet was introduced in Windows PowerShell 5.1. You don’t need to install any additional software to use PowerShell Unzip. It’s already installed on your Windows computer.

Now that you understand how the PowerShell unzip command, Expand-Archive. Let’s take a look at how to use PowerShell to extract files from a compressed archive. To use the Expand-Archive cmdlet, you need to specify the path to the ZIP file and the destination path where the extracted files will be stored. The syntax for expand-archive in PowerShell is simple:

Expand-Archive 
[-Path] <string> 
[-DestinationPath] <string> 
[-Force] 
[-WhatIf] 
[-Confirm] 
[-PassThru] 
[-LiteralPath <string>]
#Expand-Archive -LiteralPath PathToZipFile -DestinationPath PathToDestination

Expand-Archive -Path "C:\Temp\LogsArchive.zip" -DestinationPath "C:\Temp\Logs"

This command will extract all the files from the existing zipped file located at “C:\Temp\LogsArchive.zip” and place them in the folder located at “C:\Temp\Logs”. You can verify that the files were extracted correctly by navigating to the destination directory and checking that the files are there. Use quotations around the path when the file path contains a space.

PowerShell Extract Zip File

If the zip file is located in the current folder, we just need to specify the zip file using LiteralPath or Path parameter, and optionally, the DestinationPath parameter value. If the “DestinationPath” parameter is not provided, it extracts the archive to the current directory.

Expand-Archive -LiteralPath ".\Scripts.zip"

If you want to overwrite destination files during the extraction process, you can use the -Force parameter:

Expand-Archive -Path 'C:\Archives\Example.zip' -DestinationPath 'C:\ExtractedFiles' -Force

By including the -Force parameter, PowerShell will overwrite existing files with the extracted files, if necessary.

If you find yourself needing to extract multiple ZIP files in a directory, you don’t need to do this one by one. Instead, you can use PowerShell! Let’s say you want to extract all the ZIP files present in the directory “C:\Archives”. You will first need to obtain all the ZIP files in the directory and then extract them one by one. The Get-ChildItem cmdlet, and we’ll utilize a foreach loop to iterate through each file.

How do I unzip multiple files in PowerShell? Here is the PowerShell script to extract all zip files in a Folder:

Get-ChildItem "C:\Archives" -Filter *.zip | ForEach { 
    Expand-Archive -Path $_.FullName -DestinationPath "C:\Extracted" -Force
}
Extract all zip files using powershell

The above command uses the wildcard characters to get all zip files and extract them from the folder “C:\Archives” to the “C:\Extracted”.

How do I unzip multiple files in PowerShell?

Instead of all files in a directory, You can supply specific zip files to extract to a specific folder:

#Parameters
$FilesToExtract = @("C:\Archives\Backup-Set1.zip","C:\Archives\Backup-Set2.zip", "C:\Archives\Backup-Set3.zip")
$DestinationDirectory  = "C:\Extracted"

# Loop through each file and extract it
ForEach ($ZipFile in $FilesToExtract) {
    #Frame Folder to Extract
    $ExtractedFolderName = $ZipFile -replace ".zip$"
    $ExtractedFolderPath = Split-Path -Path $ExtractedFolderName -Leaf
    $DestinationPath = Join-Path -Path $DestinationDirectory -ChildPath $ExtractedFolderPath
    
    # Create the destination folder if it doesn't exist
    If (-not (Test-Path -Path $DestinationPath)) {
        New-Item -Path $DestinationPath -ItemType Directory | Out-Null
    }
    #Extract Each Archive to the Destination Folder
    Expand-Archive -Path $ZipFile -DestinationPath $DestinationPath -Force
}

Another method to unzip files using PowerShell is by using the ZipFile.ExtractToDirectory method is available in the .NET framework. This method allows you to extract files from a ZIP archive using the System.IO.Compression.ZipFile class. It is particularly useful for lower versions of .NET, such as Windows PowerShell 5.1.

Syntax of ZipFile.ExtractToDirectory

Add-Type -AssemblyName System.IO.Compression.FileSystem

[System.IO.Compression.ZipFile]::ExtractToDirectory(<SourceFile>, <DestinationPath>)

In the syntax, the <SourceFile> parameter specifies the path to the ZIP file, and the <DestinationPath> parameter specifies the folder where the extracted files will be stored.

Examples of Using ZipFile.ExtractToDirectory

Add-Type -AssemblyName System.IO.Compression.FileSystem
[System.IO.Compression.ZipFile]::ExtractToDirectory("C:\Archives\Example.zip", "C:\ExtractedFiles")

Overwriting existing files during extraction

To overwrite existing files during the extraction process, you can include a third parameter, true, in the ExtractToDirectory method:

Add-Type -AssemblyName System.IO.Compression.FileSystem
[System.IO.Compression.ZipFile]::ExtractToDirectory("C:\Archives\Example.zip", "C:\ExtractedFiles", $true)

By specifying $true, PowerShell will overwrite existing files with the archive’s contents if necessary.

Change zip compression ratio from PowerShell

To change the compression ratio of a zip file using PowerShell, use these steps:

  1. Compress-Archive -Path C:\SOURCE\PATH\TO\YOUR\FILES\* -CompressionLevel Fastest -DestinationPath C:\DESTINATION\PATH\ZIPPEDFILE.zip

    Compression ratio for zip file using PowerShell

    In the command, change the source and destination to match your specific paths.

:/>  Кнопки для снятия задачи на компьютере

If you want to specify the zip compression ratio, make sure to set the “CompressionLevel” flag with the ratio you want:

  • Fastest: It uses less time to compress files, which may result in a larger zip file.
  • NoCompression: This method uses no compression, resulting in a zip file that is the same size as the total number of uncompressed files.
  • Optimal: It uses more time but compresses the files with the highest ratio.

Once you complete the steps, the zip folder will be created using the specified compression ratio.

PowerShell’s Native Zip File Support

Compress-Archive -Path C:\Scripts\*.txt -DestinationPath C:\Scripts\Temp\Text.zip

You can see the command and the resulting ZIP file in Figure 1.

ScriptsTempText.zip

Figure 1. This is how you create a ZIP file in PowerShell.

Extracting a ZIP file’s contents is just as easy. You would use a cmdlet named Expand-Archive, requiring both the source and destination paths. For example, if you wanted to extract the contents of the recently created ZIP file and place its contents in the C:\Scripts\Extract folder, this would be the command:

Expand-Archive -Path C:\Scripts\Temp\Text.zip -DestinationPath C:\Scripts\Extract

You can see the command and the extracted files in Figure 2.

ScriptsExtract

Figure 2. PowerShell can extract a ZIP file’s contents.

How do you read the content of a zip file without unzipping it?

You can get the contents of the file without extracting it. Here is how:

Add-Type -AssemblyName System.IO.Compression.FileSystem

#Parameters
$ZipFilePath = "C:\Temp\Archive.zip"
$FileName = "Output.txt"

#Get Contents of the Zip File
$ZipContents = [System.IO.Compression.ZipFile]::OpenRead($ZipFilePath)

# Get the specific entry (file) from the zip archive
$SpecificFile = $ZipContents.GetEntry($FileName)

#Get Contents of the File
$StreamReader = [System.IO.StreamReader]::new($SpecificFile.Open()).ReadToEnd() | Write-Host       

How do I extract specific files from a zip file? To extract a specific file from the zip file, use this PowerShell script:

Add-Type -AssemblyName System.IO.Compression.FileSystem

#Parameters
$ZipFilePath = "C:\Temp\Archive.zip"
$SpecificFileName = "Output.txt"
$DestinationFilePath  = "C:\Temp\Output.txt"

Try {
    #Get Contents of the Zip File
    $ZipContents = [System.IO.Compression.ZipFile]::OpenRead($ZipFilePath)

    # Get the specific entry (file) from the zip archive
    $SpecificFile = $ZipContents.GetEntry($SpecificFileName)

    #Get Contents of the File
    $inputStream = $SpecificFile.Open()
    $outputStream = [System.IO.File]::Create($DestinationFilePath)

    # Copy the content from the input stream to the output stream
    $inputStream.CopyTo($outputStream)

    $inputStream.Close()
    $outputStream.Close()
} Finally {
    $ZipContents.Dispose()
} 

The native PowerShell methods don’t support extracting password-protected archives. So, You have to use 3rd party modules like 7zip to extract a password-protected zip file in PowerShell. Here are the steps:

Step 1: Install the “7Zip4Powershell” module

Install-Module -Name 7Zip4Powershell

To find a list of all supported commands from the module, use: Get-Command -Module 7Zip4PowerShell.

Use the Expand-7Zip cmdlet to extract the file. Set the ArchiveFileName, TargetPath, and SecurePassword to define your parameters.

Expand-7Zip -ArchiveFileName 'C:\Archives\Backup.zip' -TargetPath 'C:\Files\' -SecurePassword (Read-Host "Enter password" -AsSecureString)

This will prompt for a password for the archive.

Add more files to zip from PowerShell

To update the zip file with more files from PowerShell, use these steps:

  1. Compress-Archive -Path C:\SOURCE\PATH\TO\YOUR\FILES -Update -DestinationPath C:\DESTINATION\PATH\ZIPPEDFILE.zip

    Update zip file using PowerShell

    In the command, change the source and destination to match your specific paths.

After completing the steps, the zip folder will be updated with the new files you specified in the command.

Unzip files from PowerShell

To unzip files with PowerShell commands on Windows 10 (or 11), use these steps:

  1. Expand-Archive -Path C:\SOURCE\PATH\TO\YOUR\ZIPFILE\ZIPPED.zip -DestinationPath C:\DESTINATION\PATH\UNZIP

    Extract files from zip using PowerShell

    In the command, change the source and destination to match your specific paths.

After completing the steps, PowerShell will extract all the files and folders from the specified zip container.

Update June 13, 2024: This guide has been updated to ensure accuracy and reflect changes to the process.

Why You Can Trust Pureinfotech

Table of contents

  • Introduction to PowerShell Unzip
  • Understanding the PowerShell unzip command Expand-Archive
  • How to unzip a file using PowerShell?
  • How to extract all zip files in a folder using PowerShell
  • How do I unzip multiple files in PowerShell?
  • Using the ExtractToDirectory Method to Unzip
  • How do you read the content of a zip file without unzipping it?
  • How to extract a password-protected zip file in PowerShell?
  • Troubleshooting Common Issues with PowerShell Unzip
  • Conclusion

Conclusion

How to extract zip from the command line?

You can use the Expand-Archive cmdlet to extract a ZIP file using PowerShell. Here’s an example of the command you can use: “Expand-Archive -Path 'C:\path\to\file.zip' -DestinationPath 'C:\path\to\extract'“. Replace the paths with the actual paths to your ZIP file and the destination folder where you want to extract the files.

How to extract 7-Zip files from the command line?

To extract 7-Zip files from the command line, you can use the 7z command-line utility provided by 7-Zip. Here’s how you can extract 7-Zip files using the command line: 7z x archive.7z -oC:\Destination

How do I create a zip file in PowerShell?

To create a zip file in PowerShell, you can open it by searching for it in the Start menu and using the Compress-Archive cmdlet. Here’s an example of how to do it:
Compress-Archive -Path C:\PathToFiles -DestinationPath 'C:\Archives\MyArchive.zip' -CompressionLevel NoCompression

Can I overwrite existing files when unzipping with PowerShell?

Yes, you can use the -Force parameter with the Expand-Archive command to overwrite existing files when unzipping.

Is it possible to unzip files to the same directory they are located in?

Yes, you can unzip files to the same directory by omitting the -DestinationPath parameter or setting it to the directory of the zip file. For example, To extract the files and subfolders of a zip file to the root directory, use:
$ZipFilePath = "C:\Temp\Logs\Logs1.zip"
Expand-Archive -Path $ZipFilePath -DestinationPath (Get-Item $ZipFilePath).DirectoryName -Force

Can I unzip a specific file from a zip archive?

PowerShell’s Expand-Archive cmdlet does not directly support extracting specific files from an archive. As a workaround, you can extract all files to a temporary directory and then move the specific file(s) you need to your desired location.

Can I unzip password-protected ZIP files using PowerShell?

The built-in Expand-Archive cmdlet does not support unzipping password-protected ZIP files. However, you can use third-party modules or libraries that support password-protected ZIP files. For example, you can use the 7Zip4PowerShell module: Expand-7Zip -ArchiveFileName "C:\Archives\protected.zip" -Password "your_password" -TargetPath "C:\ExtractedFiles"

About the Author(s)

Brien Posey

Brien Posey is a bestselling technology author, a speaker, and a 20X Microsoft MVP. In addition to his ongoing work in IT, Posey has spent the last several years training as a commercial astronaut candidate in preparation to fly on a mission to study polar mesospheric clouds from space.

Оставьте комментарий