I need to create an archive of a folder with certain subfolders (having some folders/files excluded) in PowerShell using compress-archive command.
For example, here is a folder structure:
c:\Temp\Folder
log1.log
log1_1.txt
c:\Temp\Folder\Folder1\
log2.log
log2_1.log
c:\Temp\Folder\Folder2\
log3.log
log3_1.log
Need to exclude Folder2. As a result, the following folders / files have to be included to the zip file:
c:\Temp\Folder
log1.log
log1_1.txt
c:\Temp\Folder\Folder1\
log2.log
log2_1.log
Since some files are being used by another process, had to follow the recommendation below:
Compress-Archive Error: Cannot access the file because it is being used by another process
Here is a script:
Copy-Item -Path "c:\temp\folder\*" -Exclude "Folder2" -Force -PassThru | Compress-Archive -DestinationPath c:\temp1\archive.zip
However, only "c:\Temp\Folder" folder files are being included in the archive:
log1.log
log1_1.txt
Using -recurse (in Copy-Item) does include the files from Folder1, but does not keep Folder1 in the archive. So I am getting all the files from the subfolder inside archive.zip, which is not what I need.
I need the below structure of archive.zip:
log1.log
log1_1.txt
Folder1\
log2.log
log2_1.log
I tried using get-Item / get-child-Item and pipe it to copy-item - no luck - getting all files from the subfolders without folders name.
I figured out out that if I run the command below:
Copy-Item -Path "c:\temp\folder\folder1" -Force -PassThru -Recurse | Compress-Archive -DestinationPath c:\temp1\archive.zip
It creates and archive file with the below files/folders:
log2.log
log2_1.log
Folder1\
log2.log
log2_1.log
So after I deleted archive.zip and ran initial command - it is working as expected even after client reboot.
Copy-Item -Path "c:\temp\folder\*" -Exclude "Folder2" -Force -PassThru | Compress-Archive -DestinationPath c:\temp1\archive.zip
The content of zip file:
log1.log
log1_1.txt
Folder1\
log2.log
log2_1.log
I've tried it on different windows clients: win2012/2016/2019 same behavior.
If I rename c:\Temp\Folder\Folder1\ to c:\Temp\Folder\Folder3\ it stops including Folder3 folder and its contents to zip file unless I follow the above steps to get it "fixed".
Not sure why this is happening.
How to get it working properly? Appreciate your time!
Thank you!
You can try this script to achieve your requirement