Reputation: 101
I've never done Powershell before. After doing some research I wrote a script that zips a folder.
I want to make sure that I can capture any error generated during execution so I added a Try Catch block and I'm trying to log all errors. I need to make sure that the zipping process is successful.
This scripts assumes that we can add to an existing zip file if it already exist. Later on I will add a check to delete the previous zip file however for now if I leave things as is to test logging as it generates an error.
However the error is not caught and logged as expected. Any suggestions as to what I'm doing wrong? The error is a pop up window "This folder already contains a folder named 'Backups'. Rename the folder you are trying to copy and then perform the operation again.
########################################################
#
# Zip-Folder.ps1
#
# Usage:
# To zip up a folder:
# (Zip Application) (Target Archive path and File Name) (Source Folder Path to Backup) (Log Path and File Name)
# d:\zip-folder.ps1 d:\Backups_Archive d:\Backups
########################################################
try{
$target = $args[0]
$files = Get-item $args[1]
$log = $args[2]
if (-not $target.EndsWith('.zip')) {$target += '.zip'}
if (-not (test-Path $target)) {
set-content $target ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
}
$ZipFile = (new-object -com shell.application).NameSpace($target)
# $files | foreach {$zipfile.CopyHere($_.fullname)}
foreach($file in $files)
{
$zipfile.CopyHere($file.FullName)
Start-sleep -milliseconds 500
}
} catch {
Add-Content $log $error[0]
}
To execute: (Zip Application) (Target Archive path and File Name) (Source Folder Path to Backup) (Log Path and File Name) For example d:\zip-folder.ps1 d:\Backups_Archive d:\Backups d:\zip.log
Upvotes: 2
Views: 1936
Reputation: 301177
The popup that you see is being generated by the Shell. Though you can suppress the UI by passing the flag 1024
, I do not think it is possible to handle it as an error that can be caught in Powershell, because the Shell doesn't return it to the Powershell. You will have to handle the case explicitly rather than catching an error.
Also, it is generally accepted that this way of zipping files is not really very flexible and also does not really scale with large number of files ( another point being the sleep that you have in your code)
Please use some commandline zipping tool like the 7z.exe for zipping.
Upvotes: 3