Search code examples
powershellzipnode-modulessubdirectory

Powershell Zip Directory exclude some Subdirectories


I'm writing a powershell script in which I would like to .zip a directory with 2 subdirectories. In one of the subdirectories I would like to exclude another directory.

myDirectory
-- sub 1
--- sub 1.1
--- sub 1.2
-- sub 2
--- sub 2.1
--- sub 2.2

I wrote this script but it isn't working. Can anyone give me a hint or tell me what I'm doing wrong?

$ChildItemPath = "myDirectory"

$Date = [DateTime]::Now.ToString("yyyyMMdd-HHmmss")
$Exclude = @("myDirectory/sub 2/sub 2.1")

$DestinationPath = "Archive-v" + $Date

$CompressPath = Get-ChildItem -Path $ChildItemPath -Exclude $Exclude

Compress-Archive -Path $CompressPath -DestinationPath $DestinationPath -update

the .bat/.ps1 file is in the same directory as 'myDirectory'

-------------------------- EDIT 19:55 -------------------------- Solution of suggested by Reza works fine when subfolder is pretty 'small'. I'm trying to exclude 'node_modules' from a AngularClient-dir.

So the final .zip file contains a 'serverside'-dir: vs217 asp.net core project and a 'clientside'-dir: angular4 project without the node_modules


Solution

  • I know this is an old post, but I just wrote my own piece of script to Zip a Node.js Azure Function skipping node_modules folder. It's fast as it doesn't even go through the folders to skip.

    Disclaimer: it won't filter 2nd level or deeper folders in the directory tree as it's enough for my use case

    #Create temporary directory to work with
    $OutputFolderName = "HOLA - Any name of course"
    $tempFolderPath = [System.IO.Path]::GetTempPath()
    $tempFolderToCopyTo = New-Item -Path $tempFolderPath -ItemType "directory" -Name $OutputFolderName
    
    #Copy all folders to the temporary location, except the ones to exclude
    $InputFolderPath = "Full path to the folder to copy"
    $InputFoldersToSkip = @("node_modules", ".vscode")
    $childItems = Get-ChildItem -Path $InputFolderPath
    foreach ($child in $childItems) {
      if ($child.Name -in $InputFoldersToSkip) {
        continue
      }
      Copy-Item -Path $child.FullName -Destination $tempFolderToCopyTo -Recurse
    }
    
    #open file explorer there
    Invoke-Item $tempFolderToCopyTo.PSPath
    
    
    #Zip it!
    $inputItem = Get-Item -Path $InputFolderPath
    $compressParams = @{
      Path= "$($tempFolderToCopyTo.PSPath)\*"
      CompressionLevel = "Fastest"
      DestinationPath = "$($tempFolderToCopyTo.PSPath)/$($inputItem.Name)"
    }
    Compress-Archive @compressParams
    
    #After using the Zip, delete the temp folder
      Remove-Item $tempFolderToCopyTo -Force -Recurse