PowerShell: Mass Convert Zip to 7Zip or 7Zip to Zip
If you have a directory full of .zip files you want to convert to the 7zip format (or vice versa), these scripts will do that.
About, Pre-Requisites, Etc.
I wrote this script because originally I had a big directory full of .zip files and wanted to convert them to the .7z format to save some disk space. This script will take a directory you put in, get a list of .zip files in that directory, decompress them one at a time, then recompress them in .7z format.
After that, just do the following:
- Download the latest version of PowerShell and Visual Studio Code; install both (preferably in that order).
- (optional) Install desired extensions (PowerShell, themes, etc.).
- Create a Scripts directory (if it doesn’t exist). Open this directory in VSC (answer yes when asked to trust the directory).
- Copy the script to a new file and save it in your scripts directory.
- Uncomment (remove the # marks) and run the first time setup items (you can highlight them once you open the script in VSC, then select Terminal > Run Selected Text). After doing this, put the # back in.
- Change the user setting variables and transcripting options as needed.
- Run the script (Terminal > Run Active File).
Zip to 7Zip Script
<#
.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.
.PARAMETER
.EXAMPLE
.NOTES
Version History:
04272022 - Cleanup and fixes.
05162019 - First version.
.LINK
https://saturnforge.com
#>
###############################################################################
## First-Time Setup
###############################################################################
<#
This script was tested with PowerShell 7.2.2. Make sure that is installed
prior to running.
https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell
It's also recommended to download and install Visual Studio Code:
https://code.visualstudio.com/download
Make sure the PowerShell module is installed.
Below are items to run once before executing the script. Uncomment them, run
the script once, then comment them out. Also be sure to update the option
variables.
#>
## Set execution policy on the local machine
# Set-ExecutionPolicy -Scope LocalMachine -ExecutionPolicy RemoteSigned
## Module Installs
# Only uncomment ones you need to install (first time only, needs admin)
# Install-Module -name 7Zip4PowerShell
###############################################################################
## Modules
###############################################################################
## Module Updates
Update-Module -name 7Zip4PowerShell -AcceptLicense
# Import 7Zip4Powershell
Import-Module -name 7Zip4Powershell
###############################################################################
## Variables
###############################################################################
## User configurable Options
# What directory are your zip files in?
$convertDirectory = "X:\SourceDirectory\"
# Temp directory for placing extacted files
$extractDirectory = "X:\TempExtract\"
# Where do you want the new 7z files placed?
$compressDirectory = "X:\DestinationDirectory\"
## Transcripting Options
# What's the error preference?
$ErrorActionPreference = "SilentlyContinue"
$transcriptDirectory = "X:\Scripts\Logs\"
$transcriptFile = "ZipTo7z_" + (Get-Date).Month + "_" + (Get-Date).Day + "_" + (Get-Date).Year + ".txt"
$transcriptFilePath = $transcriptDirectory + $transcriptFile
###############################################################################
## Arrays & Hash tables
###############################################################################
# List of directories to check
$directoryTestList = @(
"$convertDirectory",
"$extractDirectory",
"$compressDirectory",
"$transcriptDirectory"
)
###############################################################################
## 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-Error -Message "[!] $testDirectory is inaccessible! Exiting." -ErrorAction Stop
}
}
# 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-Error -Message "[!] $testFile is inaccessible! Exiting." -ErrorAction Stop
}
}
# 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 Yellow "[^] 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-ZipTo7z {
Param ($convertDirectory)
# First we need a list of files
$fileArray = Get-ChildItem -Path $convertDirectory -Filter *.zip -Name
$fileCount = (Get-ChildItem -Path $convertDirectory -Filter *.zip).Count
$i = 0
ForEach ($file in $fileArray) {
$i++
$oldFile = $convertDirectory + $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 "[>] Extracting: $oldFile"
Expand-7Zip -ArchiveFileName $oldFile -TargetPath $extractDirectory
# Now compress the contents to a new 7z file
Write-Host -BackgroundColor Black -ForegroundColor Cyan "[>] 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
###############################################################################
# Make sure all logging is stopped, then open logs
Stop-Transcript | Out-Null
Start-Transcript -Path $transcriptFilePath -Append
## Let's get this party started at Grizzlebees
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 "[#] Beginning verification phase."
# Confirm directories exist
ForEach ($directory in $directoryTestList) {
Test-DirectoryPresence $directory
}
## RE-COMPRESSION PHASE
# Do it
Write-Host -BackgroundColor Black -ForegroundColor White "[#] Beginning conversion phase."
Convert-ZipTo7z $convertDirectory
Write-Host -BackgroundColor Black -ForegroundColor White "################################################################################"
Write-Host -BackgroundColor Black -ForegroundColor White "Conversion process complete!"
Write-Host -BackgroundColor Black -ForegroundColor White "################################################################################"
# End logging
Stop-Transcript
# You're still here? The script is over. Go home.
###############################################################################
## Scratchpad
###############################################################################
<#
#>
7Zip to Zip Script
Does the same thing as the above, just in reverse.
<#
.SYNOPSIS
Converts all 7z files in a directory to Zip files.
.DESCRIPTION
Converts all 7z files in a directory to Zip files.
Requires 7Zip4Powershell module.
.PARAMETER
.EXAMPLE
.NOTES
Version History:
04272022 - Cleanup and fixes.
03302020 - First version.
.LINK
https://saturnforge.com
#>
###############################################################################
## First-Time Setup
###############################################################################
<#
This script was tested with PowerShell 7.2.2. Make sure that is installed
prior to running.
https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell
It's also recommended to download and install Visual Studio Code:
https://code.visualstudio.com/download
Make sure the PowerShell module is installed.
Below are items to run once before executing the script. Uncomment them, run
the script once, then comment them out. Also be sure to update the option
variables.
#>
## Set execution policy on the local machine
# Set-ExecutionPolicy -Scope LocalMachine -ExecutionPolicy RemoteSigned
## Module Installs
# Only uncomment ones you need to install (first time only, needs admin)
# Install-Module -name 7Zip4PowerShell
###############################################################################
## Modules
###############################################################################
## Module Updates
Update-Module -name 7Zip4PowerShell -AcceptLicense
# Import 7Zip4Powershell
Import-Module -name 7Zip4Powershell
###############################################################################
## Variables
###############################################################################
## User configurable Options
# What directory are your zip files in?
$convertDirectory = "D:\Emulation\ROMs\MAME\ROMs\"
# Temp directory for placing extacted files
$extractDirectory = "D:\Emulation\ROMs\MAME\TempExtract\"
# Where do you want the new 7z files placed?
$compressDirectory = "D:\Emulation\ROMS\MAME\ReZip\"
## Transcripting Options
# What's the error preference?
$ErrorActionPreference = "SilentlyContinue"
$transcriptDirectory = "D:\Scripts\Logs\"
$transcriptFile = "7zToZip_" + (Get-Date).Month + "_" + (Get-Date).Day + "_" + (Get-Date).Year + ".txt"
$transcriptFilePath = $transcriptDirectory + $transcriptFile
###############################################################################
## Arrays & Hash tables
###############################################################################
# List of directories to check
$directoryTestList = @(
"$convertDirectory",
"$extractDirectory",
"$compressDirectory",
"$transcriptDirectory"
)
###############################################################################
## 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-Error -Message "[!] $testDirectory is inaccessible! Exiting." -ErrorAction Stop
}
}
# 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-Error -Message "[!] $testFile is inaccessible! Exiting." -ErrorAction Stop
}
}
# 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 Yellow "[^] 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-7zToZip {
Param ($convertDirectory)
# First we need a list of files
$fileArray = Get-ChildItem -Path $convertDirectory -Filter *.7z -Name
$fileCount = (Get-ChildItem -Path $convertDirectory -Filter *.7z).Count
$i = 0
ForEach ($file in $fileArray) {
$i++
$oldFile = $convertDirectory + $file
$newFile = $file.replace(".7z", ".zip")
$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 "[>] Extracting: $oldFile"
Expand-7Zip -ArchiveFileName $oldFile -TargetPath $extractDirectory
# Now compress the contents to a new 7z file
Write-Host -BackgroundColor Black -ForegroundColor Cyan "[>] 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
###############################################################################
# Make sure all logging is stopped, then open logs
Stop-Transcript | Out-Null
Start-Transcript -Path $transcriptFilePath -Append
## Let's get this party started at Grizzlebees
Write-Host -BackgroundColor Black -ForegroundColor White "################################################################################"
Write-Host -BackgroundColor Black -ForegroundColor White "7Z to Zip Mass Converter"
Write-Host -BackgroundColor Black -ForegroundColor White "################################################################################"
Write-Host -BackgroundColor Black -ForegroundColor White "[#] Beginning verification phase."
# Confirm directories exist
ForEach ($directory in $directoryTestList) {
Test-DirectoryPresence $directory
}
## RE-COMPRESSION PHASE
# Do it
Write-Host -BackgroundColor Black -ForegroundColor White "[#] Beginning conversion phase."
Convert-7zToZip $convertDirectory
Write-Host -BackgroundColor Black -ForegroundColor White "################################################################################"
Write-Host -BackgroundColor Black -ForegroundColor White "Conversion process complete!"
Write-Host -BackgroundColor Black -ForegroundColor White "################################################################################"
# End logging
Stop-Transcript
# You're still here? The script is over. Go home.
###############################################################################
## Scratchpad
###############################################################################
<#
#>