Convert all ZIP files to 7Z in a Directory with PowerShell

Convert all ZIP files to 7Z in a Directory with PowerShell

This is a somewhat useful script for mass converting all ZIP files in a directory to 7Z.

The use case for me was having a massive amount of ZIP files in a directory that I wanted to convert to 7Z so that I could consolidate another directory that had similar files in 7Z format. Before using, make sure you do the following:

  1. Change the directories in the Variables section.
  2. Run VS Code in Admin mode and install the 7Zip4Powershell module. (see Description section below)
  3. Put your ZIP files into the convert directory.
  4. Empty the extract directory.
<#
.SYNOPSIS
Converts all Zip files in a directory to 7z files.

.DESCRIPTION
Converts all Zip files in a directory to 7z files. 

Requires 7Zip4Powershell module. To install, use this command in admin mode:
Install-Module -Name 7Zip4PowerShell -Verbose

.PARAMETER

.EXAMPLE

.NOTES

Version History:
05172019 - Some user comfort features (progress displays)
05162019 - First version

.LINK
https://junkdrawer.saturnforge.com
#>

###############################################################################
## Modules
###############################################################################
# Need 7Zip4Powershell
Import-Module -name 7Zip4Powershell

###############################################################################
## Variables
###############################################################################
# What directory are your zip files in?
$convertDirectory = "D:\7ZConvert\ConvertDirectory\"

# Temp directory for placing extacted files
$extractDirectory = "D:\7ZConvert\TempExtract\"

# Where do you want the new 7z files placed?
$compressDirectory = "D:\7ZConvert\CompressDirectory\"

###############################################################################
## Arrays & Hash tables
###############################################################################
$directoryTestList = @(
    "$convertDirectory",
    "$extractDirectory",
    "$compressDirectory"
)


###############################################################################
## Functions
###############################################################################
## VERIFICATION FUNCTIONS
# Check a path to make sure it's there; exit if not
# COMPLETE
Function Test-DirectoryPresence {
    Param ($testDirectory)
    $testDirectory = $testDirectory.trim()
    If (Test-Path -Path $testDirectory ) {
      Write-Host -BackgroundColor Black -ForegroundColor Green "$testDirectory is present, continuing..."
    }
    Else { # Quit
      Write-Host -BackgroundColor Black -ForegroundColor Red "$testDirectory is inaccessible! Exiting..."
      Throw "Directory presence check failed."
    }
  }

# Checks to make sure a file is there; exits if not
# Needs a full path with file name
Function Test-FilePresence {
    Param ($testFile)
    $testFile = $testFile.trim()
    If (Test-Path -Path $testFile -PathType Leaf) {
        Write-Host -BackgroundColor Black -ForegroundColor Green "$testFile is present, continuing..."
    }
    Else {
        Write-Host -BackgroundColor Black -ForegroundColor Red "$testFile is inaccessible! Exiting..."
        Throw "File presence check failed."
    }
}

# Checks to make sure a directory is empty
Function Test-DirectoryEmpty {
  Param ($testDirectory)
  If ((Get-ChildItem -Path $testDirectory -File -Force).Count -gt 0) {
    Write-Host -BackgroundColor Black -ForegroundColor Red "Directory $testDirectory still has files in it. Deleting..."
    Remove-Item -Path $testDirectory -Force -Recurse
    Write-Host -BackgroundColor Black -ForegroundColor Cyan "Recreating extract directory: $testDirectory"
    New-Item -Path $testDirectory -ItemType Directory 
    Test-DirectoryPresence $testDirectory
  }
  Else {
    Write-Host -BackgroundColor Black -ForegroundColor Green "$testDirectory is empty, continuing..."
  }
}

## OTHER FUNCTIONS
# Main conversion function, needs a directory to act on
Function Convert-To7z {
    Param ($Directory)
    # First we need a list of files
    $fileArray = Get-ChildItem -Path $directory -Filter *.zip -Name 
    $fileCount = (Get-ChildItem -Path $directory -Filter *.zip).Count
    $i = 0
    ForEach ($file in $fileArray) {
      $i++
      $oldFile = $Directory + $file
      $newFile = $file.replace(".zip",".7z")
      $newFullFile = $compressDirectory + $newFile
      $progress = ($i / $filecount) * 100
      $progress = [Math]::Round($progress,2)
   
      # Write-Host -BackgroundColor Black -ForegroundColor Magenta "Old file: $oldFile"
      # Write-Host -BackgroundColor Black -ForegroundColor Magenta "New file: $newFullFile"
      Write-Host -BackgroundColor Black -ForegroundColor Cyan "Progress: $i / $fileCount ($progress %)"
      # Extract the old zip file
      Write-Host -BackgroundColor Black -ForegroundColor Cyan "`n > Extracting: $oldFile"
      Expand-7Zip -ArchiveFileName $oldFile -TargetPath $extractDirectory
      
      # Now compress the contents to a new 7z file
      Write-Host -BackgroundColor Black -ForegroundColor Cyan "`n > Compressing: $newFullFile"
      Compress-7Zip -ArchiveFileName $newFullFile -Path $extractDirectory -Format SevenZip -CompressionLevel Ultra 
      
      # Remove the extracted files
      Get-ChildItem -Path $extractDirectory -Recurse | ForEach-object {Remove-Item -Recurse -path $_.FullName }
      Test-DirectoryEmpty $extractDirectory
      
      # Check to make sure the new file is there
      Test-FilePresence $newFullFile 
    }
}


###############################################################################
## Technologic: Main Script
###############################################################################
## VERIFICATION PHASE
# Confirm the services exist; will exit if not there
Write-Host -BackgroundColor Black -ForegroundColor White "################################################################################"
Write-Host -BackgroundColor Black -ForegroundColor White "Zip to 7Z Mass Converter"
Write-Host -BackgroundColor Black -ForegroundColor White "################################################################################"
Write-Host -BackgroundColor Black -ForegroundColor White "`n >>> Beginning verification phase."

# Confirm directories exist
ForEach ($directory in $directoryTestList) {
  Test-DirectoryPresence $directory
}

## RE-COMPRESSION PHASE
# Do it
Write-Host -BackgroundColor Black -ForegroundColor White "`n >>> Beginning conversion phase."
Convert-To7z $convertDirectory

Write-Host -BackgroundColor Black -ForegroundColor White "################################################################################"
Write-Host -BackgroundColor Black -ForegroundColor White "Conversion process complete!"
Write-Host -BackgroundColor Black -ForegroundColor White "################################################################################"
# You're still here? The script is over. Go home.


###############################################################################
## Scratchpad
###############################################################################
<#

#>
Saturn Forge