Powershell Snippets: Working with Zipped Files

Ok, here’s just some basic syntax for working with Zip files with Powershell.  This was tested with Powershell 5.1…likely backwards compatible a few versions.

This does the following:

  • Creates a local folder if it doesn’t exist
  • Downloads a zip file from the web to the created local folder (URL below just a random zip I picked for testing)
  • Extracts the contents of the zip
  • Removes the zip, leaves the extracted files

#create a download directory if it doesn't exist, if it does exist, do nothing
$downloaddirectory = "C:\NewFolder"
If(Test-path $downloaddirectory) {} Else {new-item $downloaddirectory -type directory}

#download a test zip file to folder
$zipurl = 'https://www.colorado.edu/conflict/peace/download/peace.zip'
$downloadfile = $downloaddirectory + "\testfile.zip"
Invoke-WebRequest $zipurl -OutFile $downloadfile

#unzip
Add-Type -assembly "system.io.compression.filesystem"
[io.compression.zipfile]::ExtractToDirectory($downloadfile, $downloaddirectory)

#cleanup the zip
Remove-Item $downloadfile

 

And if zipping the contents back up is necessary, this will get the job done:

$zipdirectory = "C:\NewFolder"
$zipfile = "C:\test\NewFolder.zip"
Add-Type -Assembly "system.io.compression.filesystem"
$compression = [system.io.compression.compressionlevel]::Optimal
[system.io.compression.zipfile]::CreateFromDirectory($zipdirectory,$zipfile,$compression,$false)

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s