PowerShell Script to Recursively Zip All Files in Folder

I’ve enclosed a simple PowerShell script to recursively zip files using the built in shell. Works in PowerShell 2 and 3, no additional zip applications to install. I use this very useful script to tidy up a folder of trace files or backup files. To zip all files, remove the Include from the Get-ChildItem command.

# example: .\Zip-Recursively.ps1 c:\Temp\Test trc

$filePath = $args[0];
$Ext = $args[1];
if($filePath.Length -lt 3)
{
	Write-Host "Enter a path name as your first argument" -foregroundcolor Red
	return
}
if($Ext.Length -lt 1)
{
	Write-Host "Enter a file extension as your second argument" -foregroundcolor Red
	return
}
if(-not (Test-Path $filePath)) {
	Write-Host "File path does not appear to be valid" -foregroundcolor Red
	return
}
$files = Get-ChildItem $filePath -Include *.$Ext -recurse

foreach($file in $files) { 
	$fileZipName = $file.Name;

	if (-not $fileZipName.EndsWith('.zip')) {
		$fileZipName += '.zip'
	}

	$fullFilePath = $filePath + "\" + $fileZipName

	# Prepare the zip file
	set-content $fullFilePath ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))

	$shellApplication = new-object -com shell.application
	$zipPackage = $shellApplication.NameSpace($fullFilePath)

	$zipPackage.CopyHere($file.Fullname)

	# Checks each file to make sure it is added before moving to the next file
	while($zipPackage.Items().Item($file.name) -eq $null){
		Start-sleep -seconds 1
	}

	# Delete the file
	Remove-Item $file.Fullname ;

	$fullFilePath
}

Leave a Reply