function to zip and archive files separately

Welcome Forums General PowerShell Q&A function to zip and archive files separately

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

 
Participant
3 years, 9 months ago.

  • Author
    Posts
  • #24530

    Participant
    Points: 0
    Rank: Member

    I have a folder with a number of IIS Logs. I would like to zip and archive the IIS logs but when I zip and archive, I do not want to store everything in 1 zip folder. As a matter of fact, I would like to create 1 zip folder per log and want the folder to have the same basename as the log file.

    I am trying to use this function to achieve what I want:

    function add-zip{
    param($source, $destination)

    $name = Get-ChildItem $source | Select-Object basename

    foreach($obj in $name)
    {
    Add-Type -Assembly System.IO.Compression.FileSystem
    $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
    $zipfilename = $destination + "\" + $obj.BaseName + ".zip"

    [System.IO.Compression.ZipFile]::CreateFromDirectory("$source\$name",
    $zipfilename, $compressionLevel, $false)

    }
    }

    Using the function, I was able to get the zip folders to have the same name as the IIS logs themselves. However, all the zip files present at the source folder got copied inside every zip folder. How do I make sure that every zip folder only gets 1 log file?
    I would appreciate the help.

    Thanks

  • #24534

    Participant
    Points: 38
    Rank: Member

    The CreateFromDirectory method creates the .ZIP file from the specified directory. You would need to create the empty .ZIP file first and then add the file as an entry. You might want to consider installing the PowerShell Community Extensions which include a Write-Zip cmdlet. Your task then becomes as simple as:

    
    $files = Get-ChildItem F:\__Temp
    
    foreach ($file in $files) {
    
        Write-Zip $file "F:\__Temp\1\$file.zip" -Level 9
    
    }
    
  • #24552

    Participant
    Points: 0
    Rank: Member

    That worked like a charm. Thank you very much.

The topic ‘function to zip and archive files separately’ is closed to new replies.