Skip to content

Instantly share code, notes, and snippets.

@michaeloyer
Last active December 25, 2019 04:00
Show Gist options
  • Save michaeloyer/f5faab7350dce627b7f8018dfb8a9628 to your computer and use it in GitHub Desktop.
Save michaeloyer/f5faab7350dce627b7f8018dfb8a9628 to your computer and use it in GitHub Desktop.
Functions for Powershell 4 to zip files or directories (.NET Framework 4.5 Required)
Add-Type -assembly 'System.IO.Compression.FileSystem'
function Zip-Directory([string]$Directory, $Destination) {
if (!(Test-Path $Directory -PathType Container)) {
throw "Directory does not exist: $Directory"
}
$Directory = (Resolve-Path $Directory).Path.TrimEnd('\')
if ($null -ne $Destination) {
if (!(Test-Path $Destination -PathType Container)) {
throw "Destination does not exist: $Destination"
}
$Destination = (Resolve-Path $Destination).Path.TrimEnd('\')
if (($Destination + '\').StartsWith(($Directory + '\'))) {
throw "Destination cannot be in the Directory being zipped"
}
$ZipPath = [System.IO.Path]::Combine($Destination, [System.IO.Path]::GetFileName($Directory) + ".zip")
}
else {
$ZipPath = [System.IO.Path]::Combine([System.IO.Path]::GetDirectoryName($Directory), [System.IO.Path]::GetFileName($Directory) + ".zip")
}
if (Test-Path $ZipPath -PathType Leaf) {
throw "Zip File already exists: $ZipPath"
}
[System.IO.Compression.ZipFile]::CreateFromDirectory($Directory, $ZipPath)
}
function Zip-File([string]$File, $Destination) {
if (!(Test-Path $File -PathType Leaf)) {
throw "File does not exist: $File"
}
$File = (Resolve-Path $File).Path.TrimEnd('\')
if ($null -ne $Destination) {
if (!(Test-Path $Destination -PathType Container)) {
throw "Destination does not exist: $Destination"
}
$Destination = (Resolve-Path $Destination).Path.TrimEnd('\')
$ZipPath = [System.IO.Path]::Combine($Destination, [System.IO.Path]::GetFileNameWithoutExtension($File) + ".zip")
}
else {
$ZipPath = [System.IO.Path]::ChangeExtension($File, ".zip")
}
if (Test-Path $ZipPath -PathType Leaf) {
throw "Zip File already exists: $ZipPath"
}
$ZipFile = [System.IO.Compression.ZipFile]::Open($ZipPath, [System.IO.Compression.ZipArchiveMode]::Create)
$Entry = [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($ZipFile, $File, [System.IO.Path]::GetFileName($File))
$ZipFile.Dispose()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment