Script Powershell to compress old files in one zip file

Pedro_A 141 Reputation points
2021-09-28T06:45:51.697+00:00

Hello,

I need a script to compress files from the last 30 days in one zip file. I have this code that do the same but create one file for every single file:

## Adding 7zip to environment variables.
$7zippath = "$env:ProgramFiles\7-Zip\7z.exe"
Set-Alias 7zip $7zippath

## Replace x with the number of days before which the files have to be compressed.
$LastWrite = (get-date).AddDays(-30)
$date = (Get-Date).ToString('yyyyMMdd')

## Replace Path and Filter as per your need.
$Files = Get-ChildItem -Path "D:\LOGS" -Recurse -File | Where-Object {$_.LastWriteTime -le $LastWrite}


ForEach ($File in $Files) {
"Compressing Log $File"
7zip a "$($File.fullname)$date.zip" "D:\LOGS\$File"

if((Test-Path "$($File.fullname)$date.zip"))
{
"Log Compression succeeded, so deleting D:\LOGS\$File"
Remove-Item -Path "D:\LOGS\$File"
}
else
{
"Log Compression FAILED, Please check parameters are passed correctly"
}
}
```I dont know how can i zip all this files in one zipfile and name it as the last day of the month.  
  
Thanks,
OneNote
OneNote
A family of Microsoft products that enable users to capture, organize, and reuse notes electronically.
160 questions
Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,379 questions
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. Rich Matheisen 45,011 Reputation points
    2021-09-30T14:31:28.437+00:00

    If each file in your "$Files" variable has a distinct name, then you'll create a new archive file for each of them. That's just the way you wrote the 7zip command line parameters!

    If your intention is to add all the files in the $Files variable to a new (or existing) archive you should probably specify the archive name outside the ForEach loop.

    1 person found this answer helpful.
    0 comments No comments

  2. Anthony Axlen 1 Reputation point
    2021-09-30T09:37:27.157+00:00

    Hello,

    I think one of the solution could look like following:

    • create Archive folder - New-Item -Path <path> -ItemType Directory
    • move all related files to this folder
    • use Compress-Archive - examples of usage here compress-archive
    • delete folder or files if not needed

    Or you can limit it as much as possible by:

    $Files | Compress-Archive -DestinationPath <path>   
    

    Thank you.

    0 comments No comments