Function: Expand-ZipFile

Fellow coders, I’ve got a quick and dirty function for you. I had the requirement to extract zip files from a particular directory. Of course you could do this with Expand-Archive (new in PowerShell 5).

But there’s a problem with this little rascal; it does not keeps the timestamps of the zipped files intact. My customer wanted to keep these timestamps intact, because they use it as a indicator to see if the file is older or newer what they already have.

So I made a quick and dirty function, which uses a .NET assembly. I based this function on code I remembered from somebody else, but I cannot remember or find that source anymore.

This function takes in a sourcepath, which contains your zip files. The destinationpath is the place where you want to place the extracted files. The overwrite switch determines if existing files in the destinationpath has to be overwritten or not.

#requires -Version 2
function Expand-ZipFile()
{
    [CmdletBinding()]
    Param(
        [Parameter(Mandatory = $true,Position = 0)][string]$SourcePath,
        [Parameter(Mandatory = $true,Position = 1)][string]$DestinationPath,
        [Parameter(Mandatory = $true,Position = 2)][bool]$Overwrite
    )
    Add-Type -AssemblyName System.IO.Compression.FileSystem
    try
    {
        foreach($sourcefile in (Get-ChildItem -Path $SourcePath -Filter '*.ZIP'))
        {
            $entries = [IO.Compression.ZipFile]::OpenRead($sourcefile.FullName).Entries
            $entries | ForEach-Object -Process {
                [IO.Compression.ZipFileExtensions]::ExtractToFile($_,"$DestinationPath\$_",$Overwrite)
            }
        }
    }
    catch
    {
        Write-Warning -Message $_.Exception.Message
    }
}

Comments are closed.