powershell - 压缩归档并保留相对路径

标签 powershell zip

我很难获得 compress-archive做我想做的事……

我有一个根项目文件夹,我想压缩子目录中的一些文件并保留相对路径。例如: / ├── _scripts ├── ├─_module1 | | └── filex.js | └─_module2 | ├── file1.js | └── file2.txt
所以从我的根目录,我想创建一个包含 module2/* 的 zip 文件。 ,我想保留文件夹结构。我希望我的 zip 包含: scripts/module2/file1.js scripts/module2/file2.txt
但是当我从根文件夹运行它时:Compress-Archive -Path "scripts\module2\*" -DestinationPath tmp.zip
zip 文件的内容仅包含: /file1.js /file2.txt

最佳答案

看来Compress-Archive (从 Windows PowerShell v5.1 开始)不支持您想要的:

以递归方式定位文件夹会将该文件夹的子树添加到存档中,但只能通过目标文件夹的名称(成为存档内的子文件夹),而不是其路径。

具体来说,

Compress-Archive -Path scripts\module2 -DestinationPath tmp.zip

将(递归地)存储 scripts\module2 的内容在 tmp.zip ,但不包含存档内部路径 .\scripts\module2 , 只需 .\module2 - 目标文件夹的名称(最后一个输入路径组件)。

这意味着您必须传递文件夹 scripts取而代之的是获取所需的存档内部路径,但这总是包括 scripts 的整个子树,鉴于 Compress-Archive不提供包含/排除机制。

一种 - 繁琐 - 选项是在 $env:TEMP 中重新创建所需的层次结构。文件夹,将目标文件夹复制到那里,运行 Compress-Archive针对重新创建的层次结构的根,然后清理:
New-Item -Force -ItemType Directory $env:TEMP/scripts
Copy-Item -Recurse -Force scripts/module2 $env:TEMP/scripts
Compress-Archive -LiteralPath $env:TEMP/scripts -DestinationPath tmp.zip
Remove-Item $env:TEMP/Scripts -Recurse -Whatif

否则,您也许可以找到解决方案:
  • 通过使用 .NET v4.5+ [System.IO.Compression.ZipFile] class直接地;您可以使用 Add-Type -Assembly System.IO.Compression.FileSystem 将其加载到您的 session 中(在 PowerShell Core 中不需要)。
  • 通过使用外部程序,例如 7-Zip ,
  • 关于powershell - 压缩归档并保留相对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51392050/

    相关文章:

    Powershell Group-Object - 使用多个对象进行过滤

    c# - 将string []从批处理文件(包含双引号“)传递到powershell脚本

    java - 压缩存在于一个 FTP 位置的文件并直接复制到另一个 FTP 位置

    python - 使用 zip 的字典列表,将增量列表名称传递给函数

    algorithm - 如何确定 ZIP/RAR 文件的压缩方法

    python - 如何解释 ZipInfo.date_time 值

    python - 有没有办法从 bash 运行 zip 文件中的 python 脚本?

    powershell - 打印传递给 cmdlet 的所有参数

    regex - 使用Powershell和正则表达式操作String

    powershell - PowerShell 是否不为非默认端口发送身份验证 header ?