I'm trying to zip a folder but exclude multiple directories using powershell.
I got the following:
if (-not (test-path "$env:ProgramFiles\7-Zip\7z.exe")) {throw "$env:ProgramFiles\7-Zip\7z.exe needed"}
set-alias sz "$env:ProgramFiles\7-Zip\7z.exe"
$Source = "D:\Zip\*"
$Target = "D:\backup.7z"
$exclude = 'Customer\Images\*'
sz a -xr!'$Customer\Images\*' $Target $Source
This works fine.. But when I want the change the -xr!
to -xr!'$exclude'
or -xr!$exclude
it stops working for some reason. Does the variable assigned above not get parsed?
Try this...
if (-not (Test-Path "$env:ProgramFiles\7-Zip\7z.exe")) {throw "$env:ProgramFiles\7-Zip\7z.exe needed"}
$7ZipPath = "$env:ProgramFiles\7-Zip\7z.exe"
$Source = "D:\Zip\*"
$Target = "D:\backup.7z"
$foldersToExclude = 'folder1', 'folder2'
$7zipParams = @('a',$Target)
@($foldersToExclude) | ForEach-Object { $7zipParams += "`"-xr!$_`"" }
$7zipParams += $Source
Write-Host ($7ZipPath+' '+$7zipParams -join ' ') # debug - show the command line
&$7ZipPath $7zipParams
We create an array of params to pass into 7zip, including the excluded folders. As we're appending the excluded folders, we prepend the folder names with the -xr!
flags and wrap these in double qoutes.
The #debug
line outputs the resultant command line to the console
I call 7zip slightly differently to you, by creating a string with the 7zip executable, then prepending the call to that string path with an ampersand.
This method can exclude multiple folders from the final archive, including folder\\subfolder
structure.
Two things:
sz a "-xr!$exclude" $Target $Source
Customer\\Images\\*
excludes all files in the directory Images
, but includes an empty directory in the resulting file. Use Customer\\Images
if you don't want to include the directory (or any of its files).
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.