1
votes

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.

2
you can find possible answer at: stackoverflow.com/a/59018865/2349693user2349693

2 Answers

2
votes

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

0
votes

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.