Usually to create archives automatically, I use 7zip. This tool is free, convenient and has a command line interface, which allows to use it in scripts. However, it is not always possible to install a third-party software on a server, so, if necessary, ZIP archives can be created using the built-in Windows features.
To create a ZIP archive, you can use ZipFile class that appeared in .NET Framework 4.5. This class is not loaded by default, so the first thing you have to do is to add the assembly using this command:
Add-Type -Assembly “system.io.compression.filesystem”
After adding the assembly, you can create archives. To do it, use CreateFromDirectory statistic method of ZipFile class. To create an archive from a directory with this method, you have to specify a source directory and the target ZIP-file name as arguments. For instance:
$source = “C:\PoSh\TestZip”
$destination = “C:\PoSh\test.zip”
You can set the level of compression in CreateFromDirectory method:
- Optimal — optimization by the level of compression
- Fastest — optimization by the time taken
- NoCompression — without any compression
You can also specify if the archive has to be included into the base directory. As an example, let’s create another archive with Optimal level of compression and not include it into the base directory:
$level = [System.IO.Compression.CompressionLevel]::Optimal
$Include = $false
[io.compression.zipfile]::CreateFromDirectory($source, $destination, $level, $Include)
When creating an archive, remember that this method cannot rewrite the existing files and if there is a ZIP file with this name in the directory, it returns an error.
The reverse operation is decompression. To do it, use ExtractToDirectory method. To run it, you have to specify a source ZIP file and a directory to extract it to. As an example, let’s decompress the archive created earlier:
$source = ″C:\PoSh\test.zip″
$destination = ″C:\PoSh\TestZip1″
That’s all, and you can learn more about ZipFile class of .Net, its properties and methods from MSDN library.