File compression is not at all straight forward in Powershell. Using Windows compression is error-prone. It gives unexpected results and fails silently. The problem is basically with file size larger than 3 Gigs. If file-size is larger than 3 Gigs, Windows 2003 based server will not complete the task and fail silently. If you have delivered it for any critical task, you will find yourself in a real trouble.
Windows native compression method:
Below is the code which can be used :
#------------------------------------------------------------------------------------------
# Script : compress_file.ps1
# Author : Som DT.
# Purpose : Compress file script
#------------------------------------------------------------------------------------------
function compress-file ([string]$file, [string]$zipfilename)
{
echo "Compressing [$file] to [$zipfilename]."
if(-not (test-path($zipfilename)))
{
set-content $zipfilename ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
(dir $zipfilename).IsReadOnly = $false
$shellApplication = new-object -com shell.application
$zipPackage = $shellApplication.NameSpace($zipfilename)
$zipPackage.CopyHere($file)
#--Add some delay to wait -#
do {
$zipCount = $zipPackage.Items().count
echo "Waiting for compression to complete ..."
Start-sleep -Seconds 1
}
while ($zippackage.Items().count -lt 1)
echo "Finished zipping successfully"
}
}
#------------------------------------------------------------------------------------------
#--Starting comressing the file --#
compress-file "D:\new.txt" "D:\new.zip"
#------------------------------------------------------------------------------------------
This works fine with Windows 2008 and above operating system. But still there are two problems -
1. CopyHere function is a real mess. It does not stick to the point where this function is called. It moves ahead, so you need to put a logic to make the script wait till compression is over.
2. This is hard to predict if compression failed. Script might run infinite in some cases. This is genuine problem and above script is not recommended.