Home > Mobile >  How to zip specific files and folders in subdirectories using powershell
How to zip specific files and folders in subdirectories using powershell

Time:06-22

I have a folder structure for example like this

- folder1
  - folderA
  - folderB
    - backup
      - folder0
      - file1
      - file2
- folder2
  - folderX
  - folderY
    - backup
      - folder0
      - file1
      - file2

I want the files and folders (in this example 'folder0' 'file1' 'file2') that are inside the folders 'backup' in backup.zip and delete the folder 'backup' after it's done.

An example of the result I'm expecting to achieve.

- folder1
  - folderA
  - folderB
    backup.zip
- folder2
  - folderX
  - folderY
    backup.zip

This is what I have so far.

Get-ChildItem '.' -r -Filter backup| ForEach-Object {Compress-Archive $_.FullName "$($_.DirectoryName)/$($_.BaseName)" | Remove-Item template}

this creates a backup.zip file in the root directory I'm working in. And has everything including the folder 'backup' which was not required.

CodePudding user response:

The following would get all directories named backup, and iterate through them to compress their contents to a .zip beside the backup directory. Then delete the backup directory.

 Get-ChildItem '.' -r -Filter backup -Directory | ForEach-Object { Compress-Archive ($_.FullName '\*') ($_.FullName '.zip'); Remove-Item $_.FullName -r;}
  • Related