PowerShell script to clean and zip a directory

 

As part of my role I’m often sending sample code to customers. Sometimes this is a small snippet inline in an email, but often it will be a zipped up Visual Studio solution. Simply zipping up the folder as-is ends up including bin and obj directories which bloat the zip. Performing a clean in Visual Studio helps, but I ended up writing a PowerShell script to perform the directory clean. It turned out to be reasonably simply to put together:

Get-ChildItem . -recurse -force -include bin,obj,*.tmp,*.user,*.sqlsuo,*.vssscc,*.vspscc,_UpgradeReport_Files | foreach -process {Remove-Item $_.FullName -Force -Recurse}

The command performs a recursive clean starting from the current directory and removes files and directories that I’m generally not interested in including in the zip file. So far this has made a massive difference to the size of zip files that I’ve sent. Although this has proved to be a useful script, I recently spent some time updating it to perform the directory zipping. This turned out to be a little trickier and I ended up pulling snippets together from a number of sources on the internet.

$Directory = Get-Item .
$ParentDirectory = Get-Item ..
$ZipFileName = $ParentDirectory.FullName + "\" + $Directory.Name + ".zip"

if (test-path $ZipFileName) {
  echo "Zip file already exists at $ZipFileName"
  return
}

set-content $ZipFileName ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
(dir $ZipFileName).IsReadOnly = $false

$ZipFile = (new-object -com shell.application).NameSpace($ZipFileName)

$ZipFile.CopyHere($Directory.FullName)

The first few lines of this snippet set up a couple of variables to make life easier later. Then it tests if the zip already exists and bails out if so. Then we get on to the interesting task of creating the zip file using a combination of directly to the file and calling the Shell.Application object.

You can either save these as separate scripts, or combine them into a single script. Note that I’m still trying to convert to PowerShell after far too long writing batch files so I make no claims that this is the best way to write a PowerShell script. In fact I make no claims about this, so use with caution in case it deletes the document you spent all night finishing or wipes your hard drive.

Originally posted by Stuart Leeks on August 13th 2009 here.