Backup Folder as .zip using PS

Welcome Forums General PowerShell Q&A Backup Folder as .zip using PS

This topic contains 1 reply, has 2 voices, and was last updated by

 
Member
2 years, 9 months ago.

  • Author
    Posts
  • #35397

    Participant
    Points: 0
    Rank: Member

    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

  • #35408

    Member
    Points: 0
    Rank: Member

    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 }
    }
    

The topic ‘Backup Folder as .zip using PS’ is closed to new replies.