Archive files using PowerShell

In this article I will show you how to archive files using PowerShell.

Some of the administrative tasks like archiving old event logs require to use tool which will compress size of the folder.
If we want to script those task is highly recommended to archiving files using PowerShell.
PowerShell gives us possibility to archive files using .Net class called io.compression.zipfile.
Basically script require only this class to be imported, once it is done CreateFromDriectory method is used which compressing the file.

Zip-File function is using two parameters Source and Destination.
In the source you must provide path to folder which should be archived.
In the destination path to the zipped file.

Example of usage:

Zip-File -Source D:\TestFile -Destination D:\TestFileZipped


function Zip-File 
        [Parameter(Position=0, Mandatory = $false, HelpMessage="Source folder or file path", ValueFromPipeline = $true)] 
        [Parameter(Position=1, Mandatory = $false, HelpMessage="Destination path", ValueFromPipeline = $true)] 
    $DestinationZip  = $Destination+".zip"
    Write-Host $DestinationZip
    If(Test-path $DestinationZip) 
        $ChangeDestinationPath = Read-Host "Zip file $DestinationZip already exist, do you want to replace file with new version?(yes/no)"
        if($ChangeDestinationPath -eq "yes")
            Remove-item $DestinationZip

        Add-Type -assembly ""
        [io.compression.zipfile]::CreateFromDirectory($Source, $DestinationZip)
        Write-Host "File $DestinationZip was created with success."
        $Exc = $_.Exception.Message
        Write-Error "File $DestinationZip was not created. Error: $Exc"


I hope it will be usefull for som of you 😉

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.