windows - 从 powershell 递归归档某种类型的所有文件

标签 windows powershell archive

有没有办法使用压缩存档脚本,当从路径运行时:

  1. 归档与通配符过滤器匹配的所有文件(例如 *.doc)
  2. 将此类文件存档在当前文件夹和所有子文件夹中
  3. 保存相对文件夹结构(不过,使用相对或绝对的选项会很好)

我很难让它同时完成所有这三个任务。

编辑:

以下过滤器和递归,但不维护文件夹结构

Get-ChildItem -Path ".\" -Filter "*.docx" -Recurse |
Compress-Archive -CompressionLevel Optimal -DestinationPath "$pwd\doc.archive-$(Get-Date -f yyyyMMdd.hhmmss).zip"

此项不递归:

Compress-Archive -Path "$pwd\*.docx" -CompressionLevel Optimal -DestinationPath "$pwd\doc.archive-$(Get-Date -f yyyyMMdd.hhmmss).zip"

在某些时候,我有一个命令会递归但不会过滤,但现在无法返回。

最佳答案

不幸的是,自 Windows PowerShell v5.1/PowerShell Core 6.1.0 起,压缩存档 非常有限:

  • 保留子目录树的唯一方法是将目录路径传递给压缩存档

    • 不幸的是,这样做没有提供包含/排除机制来仅选择文件的子集。

    • 此外,生成的存档将在内部包含一个以输入目录命名的单个根目录(例如,如果将 C:\temp\foo 传递给压缩存档,生成的存档将包含一个 foo 目录,该目录包含输入目录的子树 - 而不是包含 C:\temp\foo内容位于顶层)。

    • 没有选项可以保留绝对路径。

  • 一个麻烦的解决方法是创建目录树的临时副本仅包含感兴趣的文件 (Copy-Item -Recurse -过滤 *.docx . $env:TEMP\tmpDir; 压缩存档 $env:TEMP\tmpDir out.zip - 请注意,将包含目录)

    • 鉴于您仍然总是会得到以存档内的输入目录命名的单个根目录,即使这可能不适合您 - 请参阅底部的替代方案。

使用替代方案可能会更好:


直接使用.NET v4.5+解决问题[System.IO.Compression.ZipFile]类:

注意:

  • 在 Windows PowerShell 中,与 PowerShell Core 不同,您通常使用 Add-Type -AssemblyName System.IO.Compression.FileSystem 手动加载相关程序集。

  • 由于自 Windows PowerShell v5.1/PowerShell Core 6.1.0 起,PowerShell 不支持隐式使用扩展方法,因此您必须显式使用 [System.IO.Compression.ZipFileExtensions]类也是如此。

# Windows PowerShell: must load assembly System.IO.Compression.FileSystem manually.
Add-Type -AssemblyName System.IO.Compression.FileSystem

# Create the target archive via .NET to provide more control over how files
# are added.
# Make sure that the target file doesn't already exist.
$archive = [System.IO.Compression.ZipFile]::Open(
  "$pwd\doc.archive-$(Get-Date -f yyyyMMdd.hhmmss).zip",
  'Create'
)

# Get the list of files to archive with their relative paths and
# add them to the target archive one by one.
$useAbsolutePaths = $False # Set this to true to use absolute paths instead.
Get-ChildItem -Recurse -Filter *.docx | ForEach-Object {
    # Determine the entry path, i.e., the archive-internal path.
    $entryPath = (
          ($_.FullName -replace ([regex]::Escape($PWD.ProviderPath) + '[/\\]'), ''), 
          $_.FullName
        )[$useAbsolutePaths]
    $null = [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile(
      $archive, 
      $_.FullName, 
      $entryPath
    )
  }

# Close the archive.
$archive.Dispose()

关于windows - 从 powershell 递归归档某种类型的所有文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52344911/

相关文章:

Python 内存 zip 库

windows - 如何确定进程是否处于死锁状态或正在等待 I/O

windows - 无论用户设置如何,如何创建没有任何框架的窗口?

windows - 自解压自检可执行文件

powershell - 更改 ACL - 递归所有目录 Powershell

powershell - 在 PSReadline 中为 Vi-Mode 重新绑定(bind) Escape

excel - 如何在 vba 代码中执行 "Save As",用日期戳保存当前的 Excel 工作簿?

xcode - 无法再在Xcode 4中存档

c++ - VC++ : How to prevent esc from closing a dialog box (not mfc)

powershell - 出现错误时跳过部分脚本