powershellsystem.io.compression

Extensions in subdirectories are not excluded in Zip archive


I have a folder with many sub directories I want to exclude some extensions, but they are only excluded from the first directory level, how to exclude from all directories.

Example of Directory (simplified)

dir: 
  - a.exe
  - z.dll
  - q.dat
  - dir1: 
    - g.exe
    - y.dll
    - r.dat

I don't want any of these extensions only the files not in dir1 are excluded.

Code (simplified)

$files = Get-ChildItem -Recurse -Path "$env:USERPROFILE\dir" -Exclude @('*.exe','*.dll', '*.dat')

Compress-Archive            `
  -Update                   `
  -Path $files              `
  -CompressionLevel Fastest `
  -Destination "$env:USERPROFILE\Desktop"

The zip file contains the extensions in dir1.


Solution

  • Compress-Archive doesn't have an -Exclude by itself to help you with this, by using -Exclude @('*.exe', '*.dll', '*.dat') with Get-ChildItem you're excluding files with those extensions in your $files variable, however because dir1 is included then all files in that folder are also compressed.

    I'd recommend to try Compress-ZipArchive instead which does have an -Exclude parameter. This way you retain the folder hierarchy while also excluding the files having those extensions:

    $compressZipArchiveSplat = @{
        Path             = "$env:USERPROFILE\dir"
        Update           = $true
        CompressionLevel = 'Fastest'
        Destination      = "$env:USERPROFILE\Desktop"
        Exclude          = '*.exe', '*.dll', '*.dat'
    }
    
    Compress-ZipArchive @compressZipArchiveSplat
    

    This cmdlet is from PSCompression Module, you can install it from the Gallery:

    Install-Module PSCompression -Scope CurrentUser