How to extract a specific folder from a zip file

Hi,

I have a zip file contains folders, sub folders and files.

I want to extract a specific sub folder along with files and folders in it.

Can anyone suggest a way to accomplish this. I tried the below code but no luck.

$xtrctfolder = "Valueadd\Data\Current\admin\production\"
$destination = "D:\Dinesh\Final_xtract"

Add-Type -Assembly System.IO.Compression.FileSystem
$zip = [IO.Compression.ZipFile]::OpenRead($sourcePath)
$zip.Entries | where {$_.Name -eq $xtrctfolder} | foreach {

$target_path = [System.IO.Path]::Combine($destination, $_.Name)
$target_folder = [System.IO.Path]::GetDirectoryName($target_path)

if(!(Test-Path $target_folder ))
{
New-Item -ItemType Directory -Path $target_folder | Out-Null
}

if(!$target_path.EndsWith("\"))
{
[System.IO.Compression.ZipFileExtensions]::ExtractToFile($_, $target_path, $true);
}
}

Thanks
Dinesh

Parents
  • Try the below. I did test this and it worked on my system.

    Clear-Host

    # Instantiate compression reference
    Add-Type -Assembly System.IO.Compression.FileSystem

    # Set working variables
    $RootPath = 'E:\Temp'
    $ZipFile = 'ZipMultiFolder.zip'
    $ZipFolder = 'SubFolder1'

    # Read the zip fiel entries and process target folder and all children
    [IO.Compression.ZipFile]::OpenRead("$RootPath\$ZipFile").Entries |
    where {$PSItem.FullName -match $ZipFolder} |
    ForEach {
        If($PSItem.Name -eq '')
        {
            # Using the extrated directory name. Create new direcory if it does not exist
            $TargetFolder = $($PSItem.FullName -split '/' | Where-Object {$_} | Select -Last 1)
            New-Item -Path $RootPath -Name $TargetFolder -ItemType Directory | Out-Null
        }
        Else
        {
            # Add extracted file to the workign directory
            $TargetFile = "$RootPath\$TargetFolder\$($PSItem.Name)"
            [IO.Compression.ZipFileExtensions]::ExtractToFile($PSItem, $TargetFile, $true)
        }
    }

    # List the extracted objects.
    Get-ChildItem -Path $RootPath -Recurse

Reply Children