functions/io/Get-FilesFromZip.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
function Get-FilesFromZip(){
    [CmdletBinding()]
    param(
        [parameter(Mandatory = $true)]
        [string]$ZipFilePath,
        [parameter(Mandatory = $true)]
        [string[]]$PathsToExtract,
        [parameter(Mandatory = $true)]
        [string]$TargetDir,
        [parameter(Mandatory = $false)]
        [string]$FlattenPath
    )

    $zip = [IO.Compression.ZipFile]::OpenRead($ZipFilePath)
    try {
        foreach($pathToExtract in $PathsToExtract){
            $zip.Entries | 
                Where-Object { $_.FullName -match $pathToExtract } | 
                ForEach-Object { 
                    $fileName = $_ -replace $FlattenPath, ""

                    $fileOrDirToExtract = "$targetDir\$fileName"

                    if($fileOrDirToExtract -match '\..*'){                
                        [System.IO.Compression.ZipFileExtensions]::ExtractToFile($_, $fileOrDirToExtract, $true) 
                    }
                    else{
                        New-Item $fileOrDirToExtract -Type Directory -Force | Out-Null
                    }
                }
        }
    }
    finally {
        $zip.Dispose()
    }
}