question

Pedro-A avatar image
0 Votes"
Pedro-A asked RichMatheisen-8856 answered

Script Powershell to compress old files in one zip file

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,

windows-server-powershell
5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

AnthonyAxlen-1458 avatar image
0 Votes"
AnthonyAxlen-1458 answered AnthonyAxlen-1458 edited

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.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

RichMatheisen-8856 avatar image
0 Votes"
RichMatheisen-8856 answered

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.

5 |1600 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.