New-Zipfile, Expand-Zipfile

There is no built-in cmdlet for zipping files, but in PowerShell 3 and .Net 4.5 (or greater) we can use the classes ZipFile and ZipArchive.
To use these new classes, use Add-Type to import the System.IO.Compression.FileSystem assembly, like so:

Add-Type -As System.IO.Compression.FileSystem [IO.Compression.ZipFile]
::CreateFromDirectory( ('C:work\demo'), "demo.zip", "Optimal", $true )

To make this a little easier to type use the Zipfile functions (from Joel Bennett), which you can download here or here.

Syntax
      New-Zipfile [-ZipFilePath] <object> [-InputObject] <string[]>
         [-Append] [-compression {Optimal | Fastest | nocompression}] [CommonParameters]

key
    -ZipFilePath    The path of the zip to create.
    -InputObject    Items that we want to add to the ZipFile.
    -Append         Append to an existing zip file instead of overwriting it.
    -Compression    The compression level (defaults to Optimal):
        Optimal   - The compression operation should be optimally compressed, even if
                    the operation takes a longer time to complete.
        Fastest   - The compression operation should complete as quickly as possible,
                    even if the resulting file is not optimally compressed.
        NoCompression - No compression should be performed on the file.
     CommonParameters:
       -Verbose, -Debug, -ErrorAction, -ErrorVariable, -WarningAction, -WarningVariable,
       -OutBuffer, -PipelineVariable, -OutVariable.

Expand a zip file to a folder:

Syntax
      Expand-ZipFile [-FilePath] <Object> [[-OutputPath] <Object>] [-Force] [<CommonParameters>]

Key
    -FilePath      The path of the zip file that needs to be extracted.
    -OutputPath    The path where we want the output folder to end up.
    -Force         Name the resulting folder the same as the archive.
    CommonParameters:
       -Verbose, -Debug, -ErrorAction, -ErrorVariable, -WarningAction, -WarningVariable,
       -OutBuffer, -PipelineVariable, -OutVariable.

To make these Zip functions available all the time, add them to your PowerShell profile.

Examples

Zip the folder C:work\demo:

PS C:\> New-Zipfile 'c:\scripts\demo.zip' 'C:work\demo'

Un-Zip the file backup.zip:

PS C:\> Expand-Zipfile 'c:\scripts\backup.zip'

“Since time is the one immaterial object which we cannot influence--neither speed up nor slow down, add to nor diminish--it is an imponderably valuable gift” ~ Maya Angelou

Related:

Functions and Filters - Named blocks of code.


© Copyright SS64.com 1999-2014
Some rights reserved