17

I'm trying to zip up log using DotNetZip and powershell. The files are in C:\user\temp\logs When I loop through the logs in the directory and add them to the zip file, I end up with the folder hierarchy and the log files when I only want the log files.

So the zip ends up containing:

-user
  └temp  
    └logs
       └log1.log
        log2.log
        log3.log

When I want the zip file to contain is:

log1.log
log2.log
log3.log

Here is the script I'm running to test with:

[System.Reflection.Assembly]::LoadFrom("c:\\\User\\bin\\Ionic.Zip.dll");
$zipfile = new-object Ionic.Zip.ZipFile("C:\user\temp\logs\TestZIP.zip");

$directory = "C:\user\temp\logs\"
$children = get-childitem -path $directory
foreach ($o in $children)
{
   if($o.Name.EndsWith(".log")){
      $e = $zipfile.AddFile($o.FullName)
   }
}
$zipfile.Save()
$zipfile.Dispose()
ProfessionalAmateur
  • 4,447
  • 9
  • 46
  • 63

2 Answers2

22

There is an AddFile where you can override the filename in the archive:

public ZipEntry AddFile(
    string fileName,
    string directoryPathInArchive
)

fileName (String)

The name of the file to add. The name of the file may be a relative path or a fully-qualified path.

directoryPathInArchive (String)

Specifies a directory path to use to override any path in the fileName. This path may, or may not, correspond to a real directory in the current filesystem. If the files within the zip are later extracted, this is the path used for the extracted file. Passing null (Nothing in VB) will use the path on the fileName, if any. Passing the empty string ("") will insert the item at the root path within the archive.

Try this:

 $e = $zipfile.AddFile($o.FullName, $o.Name)

It is also possible that this does what you want:

 $e = $zipfile.AddFile($o.FullName, "")
Anders Lindahl
  • 41,582
  • 9
  • 89
  • 93
1

Not tested, but I think this should work.

[System.Reflection.Assembly]::LoadFrom("c:\\\User\\bin\\Ionic.Zip.dll");
$zipfile = new-object Ionic.Zip.ZipFile("C:\user\temp\logs\TestZIP.zip");

    $directory = "C:\user\temp\logs\"
    set-location $directory
    $children = get-childitem *.log
    foreach ($o in $children)
    {
        $e = $zipfile.AddFile($o.Name)
       }
    }
    $zipfile.Save()
    $zipfile.Dispose()
Alexan
  • 8,165
  • 14
  • 74
  • 101
mjolinor
  • 66,130
  • 7
  • 114
  • 135
  • One reason this would not work is that Set-Location does not change the current directory for the process. Any paths that you pass to methods on objects are relative to the process' current directory. This seems to be a very common pitfall with PowerShell. – OldFart Jun 01 '11 at 14:52