How to Zip a folder skipping some sub folders in powershell.

This topic contains 2 replies, has 2 voices, and was last updated by  js 1 week, 2 days ago.

  • Author
  • #102115

    Dinesh Kumar


    I have a code like below. In the source folder I have folders, sub folders and files.
    I need to zip the entire source folder and place the zip file in to some location, while zipping I need to skip one specific folder. But when am trying with below its not working. I need to have only one zip file without specific folder in that.
    Could anyone please suggest a way on this.

    $sourcePath = 'D:\Dinesh\lob1\lata'
    $destination = 'E:\Kumar\lob1\lata\'
    $excludefolder = 'processarea'

    If(Test-Path $destination)
    Remove-Item -Path $destination -Force -ErrorAction Stop

    $items = Get-ChildItem -Path $sourcePath -Recurse -Exclude $excludefolder

    Add-Type -AssemblyName ""

    $items | Foreach{


  • #102166


    Maybe this, but $excludefolder may have to be the full path, without a slash on the end (and double backslashes in windows for the regex).

    $items = Get-ChildItem -Path $sourcePath -Recurse | where fullname -notmatch $excludefolder  

    Anyone know why "test-path $file -pathtype leaf" doesn't always work in this case? (I also tried $myfile.) I'm trying "ls -r foo | .\myzip". EDIT: "$file | test-path -pathtype leaf" works every time. EDIT2: I see, the string version of $file wasn't the full path. Corrected script.

    # myzip.ps1                                                                     
    # doesn't zip empty folders
    Begin {
      if (test-path $zipfile) {
        'zipfile exists'
        exit 1
      Add-Type -AssemblyName ''
      # update or create                                                            
      $zip = [System.IO.Compression.ZipFile]::Open($zipfile,'create')
    Process {                                         
      if ($file | test-path -pathtype leaf) {
        $rel = $file | resolve-path -relative
        $rel = $rel -replace '^\.\\','' # take .\ off front                         
        $rel = $rel -replace '^\./',''  # osx take ./ off front
        # destination, sourcefilename, entryname, compressionlevel                  
          $rel, $rel, 'optimal')
      } elseif ($file | test-path -pathtype container) {
        "$file is container"
      } else {
        "$file is unknown"
    End {
  • #102418


    I don't know about you, but I think this script is pretty cool.

You must be logged in to reply to this topic.