Skip to content

Instantly share code, notes, and snippets.

@BurstX
Last active May 8, 2022 10:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BurstX/d0dc105f7d01f050459188abd18fa8bf to your computer and use it in GitHub Desktop.
Save BurstX/d0dc105f7d01f050459188abd18fa8bf to your computer and use it in GitHub Desktop.
This script archives documents in a folder (and its subfolders) that may benefit from archiving (i.e. jpg, epub are skipped; pdf's and other files are left archived if they can be compressed to a certain percentage, etc.)
<#
.SYNOPSIS
.PARAMETER Ratio
A real number within (0, 1). Ratio of the compressed file that is accepted as the archive.
Files that cannot be compressed better or equal to this ratio compared to the original,
are not archived (left as is).
#>
param(
$Ratio = 0.97
)
$7zFound = $true
try{
7z.exe | out-null
}
catch{
$7zFound = $false
}
if(-not $7zFound -or $LASTEXITCODE -ne 0 -or -not $?){
write-host "7z.exe not found" -ForegroundColor Red
write-host "Add 7z.exe to your PATH environment variable" -ForegroundColor Yellow
exit
}
$skippedFileExt = @(
'zip',
'7z',
'arj',
'rar',
'epub',
#'mp4',
'mpeg',
'png',
'jpeg',
'jpg',
'png',
'webp'
)
$files = Get-ChildItem -Recurse -File
$fileCnt = $files.Length
$fileNum = 1
foreach($file in $files){
Write-Progress -Activity "Archiving files..." -Status "Complete:" -PercentComplete $($fileNum++ * 100 / $fileCnt)
if($file.Name -eq 'book-archiver.ps1') {
continue
}
# TODO: exclude folders with 'video' in their names
$fileExt = [System.IO.Path]::GetExtension($file).ToLower()
if([string]::IsNullOrWhiteSpace($fileExt)) {
write-host "File $file does not have extension" -ForegroundColor Red
exit
}
$fileExt = $fileExt.Substring(1)
$filePath = $file.FullName
$filePathWithoutExt = $filePath.Remove($file.FullName.Length - $fileExt.Length - 1)
# remove certain files, because I personally don't need them
if($fileExt -eq 'zip' `
-and (
$filePathWithoutExt.EndsWith("_code") `
-or $filePathWithoutExt.EndsWith("-code") `
-or $filePathWithoutExt.EndsWith("_master") `
-or $filePathWithoutExt.EndsWith("-master") `
-or $filePathWithoutExt.EndsWith("_main") `
-or $filePathWithoutExt.EndsWith("-main") `
))
{
rm $filePath
continue
}
# archiving
if($skippedFileExt.IndexOf($fileExt) -gt -1){
continue
}
$archPath = $filePath + '.7z'
$archErr = $false
try{
7z.exe a -mx9 $archPath $filePath # | out-null
}
catch{
$archErr = $true
}
if($archErr -or $LASTEXITCODE -ne 0 -or -not $?){
write-host "Error archiving $filePath" -ForegroundColor Red
exit
}
$size = (Get-item $filePath).Length
$archSize = (Get-item $archPath).Length
if([float]$archSize / $size -gt $Ratio){
rm $archPath
}
else {
rm $filePath
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment