1

Inside c:\test\ I have:

  • .\dir1
  • .\dir2
  • .\dir3

and

  • file1.txt
  • file2.txt
  • file3.txt
  • file4.txt

I want to compress only dir1, dir2, file1.txt and file2.txt

I use the following script to compress selected folders

$YourDirToCompress="C:\test\"
$ZipFileResult=".\result.zip"
$DirToInclude=@("dir1", "dir2")

Get-ChildItem $YourDirToCompress -Directory  | 
           where { $_.Name -in $DirToInclude} | 
              Compress-Archive -DestinationPath $ZipFileResult -Update

How would I be able to add my selected files (file1.txt & file2.txt) to final compressed result.zip?

Ideally I want the compression to happen in one go meaning I pass the list of selected files and folders and then do the compression.

henrycarteruk
  • 12,708
  • 2
  • 36
  • 40
MHOOS
  • 5,146
  • 11
  • 39
  • 74

2 Answers2

2

Try something like this:

Get-ChildItem -Path $YourDirToCompress | Where {$_.Name -in $DirToInclude} | Compress-Archive -DestinationPath $ZipfFileResult -Update

Compress-Archrive is capable of zipping both files and directories. So in this code we are using Get-ChildItem without the -Directory flag which will return all files and directories at the root-level of $YourDirToCompress

Then we pass those files/folders to the Compress-Archive cmdlet just as we did before.

Assuming that the files are at the root level of $YourDirToCompress

Christopher
  • 790
  • 12
  • 30
0

If you compress a folder, all files and subfolders are also compressed.

So, what effort to compress specific files in a folder that you've already compressed?

Are you saying the files only live in \dir3?

If so, you just use a for loop and if statement. Match dir1 and dir2 then compress, then match file1 and file2 in dir3 then compress.

Jithin Raj P R
  • 6,667
  • 8
  • 38
  • 69
postanote
  • 15,138
  • 2
  • 14
  • 25