Creating a logical folder structure when creating a 7-Zip archive via the command-line Creating a logical folder structure when creating a 7-Zip archive via the command-line powershell powershell

Creating a logical folder structure when creating a 7-Zip archive via the command-line


If you simply want to zip up everything in the folder, then you could do this it will maintain folder structure.

."C:\Program Files\7-Zip\7z.exe" a -mx9 "C:\_test\20210112 Testing.7z" "C:\_test\*"

EDIT: To selectively archive certain files, use relative paths. In your case, you could set C:\_test as your current directory and then run

."C:\Program Files\7-Zip\7z.exe" a -mx9 "C:\_test\20210112 Testing.7z" "Data\Testing\data.txt" "Logs\Testing\data.txt"


Interesting question. I'm using 7z regularly, but never did I need such a workflow.

As you know you are getting the error due to the fact that in the archive you have duplicate file in flat structure. The 7z archiver does not know which one to used, thus the error.

I think you were quite close, but the issue is that you are using fully classified path to access the files for packing.

Solution

Your solution is to run the 7z from C:\_test\:

"C:\Program Files\7-Zip\7z.exe" a -mx9 -spf2 "C:\_test\20210112_Testing.7z" "Data\Testing\data.txt" "Logs\Testing\data.txt"

Now your archive will have the different path for the same file name. I also recommend not using space in the 7z file name - you will save yourself troubles in the future. The -spf2 switch will adjust if you have relative or absolute path based on the input. I tend to have it there if I should need to mix it.

Note

I like to use the -spf2 (does not include the drive letter in the full path) switch as that makes life easier when switching among OS.


Is there a way in 7-Zip to allow it to create a logical folderstructure when adding items from the command line?

To be clear, I'm selecting a subset of the files in the folders to bearchived and I want to place them in logical folders.

Unfortunately, no, there is no such way in 7-Zip. The author confirmed that on his sourceforge site in 2015. Since then, there has not been any update on this.

The built-in PowerShell cmdlet Compress-Archive also does not support such a feature.


You can only achieve this by an obvious workaround: Create your logical folder structure temporarily, copy your files to it, archive this temporary folder structure and delete it afterwards. If you want to preserve the timestamps of your files - which will be altered by a regular copy operation - you can use Robocopy.exe (already built-in in Windows) in connection with the /COPY:DAT /DCOPY:DAT parameters to perform the copy operation.