Last active
June 22, 2020 19:55
-
-
Save peaeater/f6c6c61e6e404f4e3ac1aa76a971c083 to your computer and use it in GitHub Desktop.
Zip textbases with System.IO.Compression
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
Zip up textbase files in preparation for FTP sync to Andornot. | |
Peter Tyrrell, ptyrrell@andornot.com | |
-textbases c:\path\to\accessions.tba, c:\path\to\descriptions.tba | |
-out c:\path\to\destination | |
#> | |
param ( | |
[string[]] $textbases, | |
[ValidateScript( { | |
if (-not ($_ | test-path -PathType Container)) { | |
throw "Out argument must be a valid folder" | |
} | |
return $true | |
})] | |
[string] $out | |
) | |
Add-Type -AssemblyName System.IO.Compression | |
Add-Type -AssemblyName System.IO.Compression.FileSystem | |
foreach ($tba in $textbases) { | |
if (-not ($tba | test-path)) { | |
throw "File or folder does not exist: $tba" | |
} | |
if (-not ($tba | test-path -PathType Leaf)) { | |
throw "Textbase argument must be a file, not a folder: $tba" | |
} | |
if ($tba -notmatch "(\.tba)") { | |
throw "Textbase argument must be of type .tba: $tba" | |
} | |
# handy things | |
$textbaseName = [System.IO.Path]::GetFileNameWithoutExtension($tba) | |
$outfile = [System.IO.Path]::Combine($out, [System.IO.Path]::ChangeExtension($textbaseName, ".zip")) | |
# get all textbase files, exclude non-critical ones | |
$files = get-childitem -path ([System.IO.Path]::ChangeExtension($tba, "*")) -File -Exclude *.7z, *.chk, *.dmp, *.log, *.tbb, *.tbu, *.zip | |
# create zip named after textbase, deleting any previously created zip | |
if (test-path $outfile) { | |
Remove-Item $outfile | |
} | |
try { | |
$z = [System.IO.Compression.ZipFile]::Open($outfile, [System.IO.Compression.ZipArchiveMode]::Create) | |
foreach ($file in $files) { | |
[System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($z, $file, [System.IO.Path]::GetFileName($file), [System.IO.Compression.CompressionLevel]::Optimal) | |
} | |
} | |
catch [System.IO.IOException] { | |
write-host "IO exception. $_" | |
# destroy incomplete zip | |
$z.Dispose() | |
Remove-Item $outfile | |
# create new zip file that contains error text | |
$z = [System.IO.Compression.ZipFile]::Open($outfile, [System.IO.Compression.ZipArchiveMode]::Create) | |
$entry = $z.CreateEntry("$textbaseName-IOException.txt") | |
$writer = [System.IO.StreamWriter]::new( $entry.Open() ) | |
$writer.Write($_) | |
$writer.Close() | |
# skip to next database | |
continue | |
} | |
finally { | |
$z.Dispose() | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment