title: Most elegant way to extract a directory from a zipfile using PowerShell?
body: <p>I need to unzip a specific directory from a zipfile.</p>
  
  <p>Like for example extract the directory 'test\etc\script' from zipfile 'c:\tmp\test.zip' and place it in c:\tmp\output\test\etc\script.</p>
  
  <p>The code below works but has two quirks:</p>
  
  <ul>
  <li><p>I need to recursively find the directory ('script') in the zip file (function finditem) although I already know the path ('c:\tmp\test.zip\test\etc\script')</p></li>
  <li><p>With CopyHere I need to determine the targetdirectory, specifically the 'test\etc' part manually</p></li>
  </ul>
  
  <p>Any better solutions? Thanks.</p>
  
  <p>The code:</p>
  
  <pre><code>function finditem($items, $itemname)
  {
    foreach($item In $items)
    {
      if ($item.GetFolder -ne $Null)
      {
        finditem $item.GetFolder.items() $itemname
      }
      if ($item.name -Like $itemname)
      {
          return $item
      } 
    } 
  } 
  
  $source = 'c:\tmp\test.zip'
  $target = 'c:\tmp\output'
  
  $shell = new-object -com shell.application
  
  # find script folder e.g. c:\tmp\test.zip\test\etc\script
  $item = finditem $shell.NameSpace($source).Items() "script"
  
  # output folder is c:\tmp\output\test\etc
  $targetfolder = Join-Path $target ((split-path $item.path -Parent) -replace '^.*zip')
  New-Item $targetfolder -ItemType directory -ErrorAction Ignore
  
  # unzip c:\tmp\test.zip\test\etc\script to c:\tmp\output\test\etc
  $shell.NameSpace($targetfolder).CopyHere($item)
  </code></pre>