Skip to content

Instantly share code, notes, and snippets.

@peaeater
Created October 24, 2016 21:40
Show Gist options
  • Select an option

  • Save peaeater/5f08daf6ba02429c4491144ee062ecdc to your computer and use it in GitHub Desktop.

Select an option

Save peaeater/5f08daf6ba02429c4491144ee062ecdc to your computer and use it in GitHub Desktop.
Picks up zip files in a given folder and extracts the contents to a destination folder.
<#
Picks up zip files in a given folder and extracts the contents to a destination folder.
Peter Tyrrell, Andornot
#>
param(
[Parameter(Mandatory=$true,Position=0)]
[string]$in,
[Parameter(Mandatory=$false,Position=1)]
[string]$out = ".",
[Parameter(Mandatory=$false,Position=2)]
[string]$newZipPath = ""
)
# validate zip file
$zipPath = [System.IO.Path]::Combine($pwd, $in)
if (-not (test-path -path $zipPath)) {
write-warning "Cannot find path '$zipPath' because it does not exist."
exit 1
}
if (-not ((get-item $zipPath).Extension -eq ".zip")) {
write-warning "Input has to be a .zip file."
exit 1
}
# validate out dir
$outPath = [System.IO.Path]::Combine($pwd, $out)
if (([System.IO.Path]::HasExtension($outPath))) {
write-warning "Extract location has to be a folder."
exit 1
}
Add-Type -AssemblyName System.IO.Compression.FileSystem
$tempPath = [System.IO.Path]::GetTempPath()
$extractFolderName = [System.IO.Path]::GetRandomFileName()
$extractPath = [System.IO.Path]::Combine($tempPath, $extractFolderName)
# unzip to temp dir
[System.IO.Compression.ZipFile]::ExtractToDirectory($zipPath, $extractPath)
# move unzipped files to output dir, overwrite pre-existing
if (-not (test-path $outPath)) {
mkdir $outPath
}
get-childitem -path $extractPath -recurse | move-item -destination $outPath -force
# move/rename input zip file
if ($newZipPath.trim() -ne "") {
mv -path $zipPath -destination $newZipPath -force
}
exit 0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment