Creating a zipped/compressed folder in Windows using Powershell or the command line
command-line, compression, powershell, windows
Solution
Here's a couple of zip-related functions that don't rely on extensions: Compress Files with Windows PowerShell.
The main function that you'd likely be interested in is:
function Add-Zip
{
param([string]$zipfilename)
if(-not (test-path($zipfilename)))
{
set-content $zipfilename ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
(dir $zipfilename).IsReadOnly = $false
}
$shellApplication = new-object -com shell.application
$zipPackage = $shellApplication.NameSpace($zipfilename)
foreach($file in $input)
{
$zipPackage.CopyHere($file.FullName)
Start-sleep -milliseconds 500
}
}
Usage:
dir c:\demo\files\*.* -Recurse | Add-Zip c:\demo\myzip.zip
There is one caveat: the `shell.application` object's `NameSpace()` function fails to open up the zip file for writing if the path isn't absolute. So, if you passed a relative path to `Add-Zip`, it'll fail with a null error, so the path to the zip file must be absolute.
Or you could just add a `$zipfilename = resolve-path $zipfilename` at the beginning of the function.
Problem
I am creating a nightly database schema file and would like to put all the files created each night, one for each database, into a folder and compress that folder. I have a PowerShell script that creates the schema.Only creation script of the db's and then adds all the files to a new folder. The problem lies within the compression portion of this process. Does anybody have any idea if this can be accomplished with the pre-installed Windows utility that handles folder compression? It would be best to use that utility if possible rather than something like 7zip (I don't feel like installing 7zip on every customers' server and it may take IT years to do it if I ask them).