简体   繁体   中英

Powershell - Add folder/files to zip while excluding certain folders

I'm trying to feed the results of a Get-ChildItem call through io.compression.zipfile to create a zip file of "E:\\Applications_Server_Test", excluding two folders "BACKUP" and "BACKUP2".

However, Powershell seems to be interpreting this as "$items = a string of directories and file names" instead of a recursive collection of directories and files I want to zip. I can find tutorials on using Get-ChildItem to exclude directories and I can find tutorials on how to zip a full directory or zip multiple directories but I can't find anything on zipping directories with exclusions. Can somebody tell me where I'm going wrong?

$source = "E:\Applications_Server_Test"
$destination = "E:\AST_Dump.zip"

$items = Get-ChildItem $source -Recurse | ?{ $_.fullname -notmatch "\\backup\\?" }

Add-Type -assembly "system.io.compression.filesystem"
[io.compression.zipfile]::CreateFromDirectory($items, $destination)

Thanks!

At the moment you are trying to archive the object $items, not the folder. Unfortunately this is not gonna work. Try to move the backup folders at the same drive (this will just change records at the drive and not move any data), then to archive the whole "E:\\Applications_Server_Test" folder and to move back the backup folders.

Other option is to use ZipArchive.CreateEntry method and to add file by file in to the archive. But this is not so elegant ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM