CodeX
CodeX

Reputation: 61

How to move files into a folder and then zip the folder in powershell

I have a powershell script that lists the files inside a folder based on a specific condition. I need to move all those files into a folder and then zip it. Can someone help me on how to do this please? I am a beginner in powershell :(

This is what I have done till now:

   #List all the folders in G:\logfiles
   $folders = (Get-ChildItem -Path "G:\logfiles" | Where-Object {$_.Attributes -eq "Directory"} | Select Fullname)

   #looping all folders
   Foreach ($folder in $folders)
   {
          $files = Get-ChildItem -Path G:\logfiles\$folder | Where{$_.LastWriteTime -lt (Get-Date).AddDays(-30)
   }

Upvotes: 1

Views: 6974

Answers (2)

C Niemi
C Niemi

Reputation: 1

This is what I have been using for a while, as long as you have 7zip installed. I agree with the above statements about PS 5 though.

#  setting variable for 7zip
if (-not (test-path "$env:ProgramFiles\7-Zip\7z.exe")) {throw "$env:ProgramFiles\7-Zip\7z.exe needed"}
set-alias sz "$env:ProgramFiles\7-Zip\7z.exe"


# adding files to zip archive, then removing all the working folders
sz a -tzip $destination $folder

I got this info from this link. Hope you get it all figured out!

Upvotes: 0

bmdixon
bmdixon

Reputation: 352

If you are able to use Powershell 5.0 then you can simply pipe the files to the Compress-Archive cmdlet (e.g. Compress-Archive -DestinationPath 'Archive.zip').

You can also simplify your script by specifying the -recurse parameter to Get-ChildItem so you don't need to loop over each folder separately (assuming this is what you want)

Get-ChildItem -recurse -Path "G:\logfiles" | Where{$_.LastWriteTime -lt (Get-Date).AddDays(-30) | Compress-Archive -DestinationPath 'Archive.zip'

Upvotes: 2

Related Questions