Search code examples
powershellzipunzippowershell-4.0

Zip and Unzip File in Powershell 4


I am using Windows Server 2012 R2 (64 bit). I have powershell version 4 available in it. I am trying to zip and unzip files. When I try Write-Zip command, it throws me following error:

Write-Zip : The term 'Write-Zip' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.

What should I do to fix it? Do I need to install zip/winrar in the server? Or is there any other command do zip/unzip files?


Solution

  • Write-Zip seems to be part of http://pscx.codeplex.com/ that require a separate installation before you can use it.

    However, if you just want to create a Zip archive from a folder, you could just run

    $source = "c:\temp\source"
    $archive = "c:\temp\archive.zip"
    
    Add-Type -assembly "system.io.compression.filesystem"
    [io.compression.zipfile]::CreateFromDirectory($source, $archive)
    

    This utilizes the CreateFromDirectory method from the .NET Framework class ZipFile. It creates a zip archive from the files located inside the $source folder and creates an archive as defined in the $archive variable. Note, ZipFile class was introduced in .NET Framework 4.5