如何在PowerShell中使用DotNetZip仅压缩文件而不压缩完整路径层次结构?

Pro*_*eur 16 powershell dotnetzip

我正在尝试使用DotNetZip和powershell压缩日志.这些文件位于C:\ user\temp\logs当我遍历目录中的日志并将它们添加到zip文件时,当我只想要日志文件时,我最终得到了文件夹层次结构和日志文件.

因此拉链最终包含:

-user
  ?temp  
    ?logs
       ?log1.log
        log2.log
        log3.log
Run Code Online (Sandbox Code Playgroud)

当我想要包含的zip文件是:

log1.log
log2.log
log3.log
Run Code Online (Sandbox Code Playgroud)

这是我正在运行以测试的脚本:

[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()
Run Code Online (Sandbox Code Playgroud)

And*_*ahl 21

有一个AddFile,您可以在其中覆盖存档中的文件名:

public ZipEntry AddFile(
    string fileName,
    string directoryPathInArchive
)
Run Code Online (Sandbox Code Playgroud)

fileName(String)

要添加的文件的名称.文件的名称可以是相对路径或完全限定路径.

directoryPathInArchive(String)

指定用于覆盖fileName中任何路径的目录路径.该路径可以或可以不对应于当前文件系统中的真实目录.如果稍后提取zip中的文件,则这是用于提取文件的路径.传递null(在VB中为Nothing)将使用fileName上的路径(如果有). 传递空字符串("")将在归档中的根路径中插入项目.

试试这个:

 $e = $zipfile.AddFile($o.FullName, $o.Name)
Run Code Online (Sandbox Code Playgroud)

也可能这样做你想要的:

 $e = $zipfile.AddFile($o.FullName, "")
Run Code Online (Sandbox Code Playgroud)