Author Posts

February 17, 2016 at 11:04 pm

Hi Team,

I have wrote below lines in PS for take daily backup of application INSTALLDIR.

Note: INSTALLDIR is "C:\PF\ApplicationName\" and contains many folders, sub folders and many files.

Add-Type -assembly "system.io.compression.filesystem"

[io.compression.zipfile]::CreateFromDirectory($Source, $destinationFile)

Case 1: If no file is in USE from INSTALLDIR while running the PS script, Backup .Zip file successful.
Case 2: If any file is in USE from INSTALLDIR while running the PS script, Full Backup .Zip un-successful.

I need your help in Case 2 for taking backup of INSTALLDIR successful even file in use (i mean we can skip the in USE file in backup process) please.

Thanks
Reddy

February 18, 2016 at 4:59 am

I've searched around a bit on this, and it looks like that's possible, but it requires you to create the ZipArchive object first, enumerate the files yourself, and add them each individually with the CreateEntryFromFile method (https://msdn.microsoft.com/en-us/library/hh485720.aspx). Then you can catch (and ignore) the IOExceptions that come from a file that can't be read. Something like this:

Add-Type -assembly "system.io.compression.filesystem"

function Get-RelativePath
{
    param ( [string] $Path, [string] $RelativeTo )
    return $Path -replace "^$([regex]::Escape($RelativeTo))\\?"
}

$archive = $null
try
{
    $archive = [System.IO.Compression.ZipFile]::Open($destinationFile, 'Create')

    Get-ChildItem $Source -File -Recurse |
    ForEach-Object {
        $file = $_
        $relativePath = Get-RelativePath -Path $file.FullName -RelativeTo $source

        try
        {
            $null = [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($archive, $file.FullName, $relativePath)
        }
        catch [System.IO.IOException] { }
    }
}
finally
{
    if ($archive) { $archive.Dispose(); $archive = $null }
}