powershell - 将选定目录中的文件添加到 7-zip 存档,同时在存档中保留相对目录结构

标签 powershell relative-path 7zip

我正在尝试压缩包含子目录的目录中的文件,但我不知道如何压缩文件而不是子目录。

这是当前的设置:

C:\users\user\appdata\local\folder\

在此文件夹中,我需要其中 20 个左右的文件夹中的 3 个,因此我使用 Get-Childitem 来完成此操作:

GCI C:\users\user\appdata\local\folder | ? {$_.name -like "*folder*}

现在我有了它,我不需要子目录,只需要文件夹本身中的文件。我还没有找到一种方法来做到这一点,但我已经接近使用这个:

& "C:\program files\7-zip\7z.exe" "a" "D:\TestBackup\Zipfile.7z" (GCI C:\users\user\appdata\local\folder | ? {$_.name -like "*folder*} | select -expandproperty FullName)

但这给了我文件夹的全部内容。我想保留结构,使其看起来像这样:

folder 1\files
folder 2\files
folder 3\files

我希望我能很好地解释自己。这些文件都是不同类型的扩展名,所以我想要一种通用的方式来执行此操作或在压缩时排除子目录。

最佳答案

我不得不咨询FAQ要做到这一点:

7-Zip stores only relative paths of files (without drive letter prefix). You can change current folder to folder that is common for all files that you want to compress and then you can use relative paths:

cd /D C:\dir1\   
7z.exe a c:\a.7z file1.txt dir2\file2.txt

解决方案:

# Set base directory that is common for all files
Push-Location 'C:\users\user\appdata\local\folder'

# Get names of directories that match filter
$folderNames = (Get-ChildItem -Directory -Filter '*folder*').Name

# Call 7-zip, passing the list of directory names.
& 'C:\Program Files\7-Zip\7z.exe' a 'D:\TestBackup\Zipfile.7z' $folderNames

# Restore current directory
Pop-Location

备注:

  • Push-Location 设置当前目录,而 Pop-Location 恢复之前的当前目录。如 7-zip FAQ 所述,更改当前目录对于此解决方案至关重要。这也是为 Resolve-Path -Relative 设置基本目录的唯一方法。
  • 如果您只对目录或文件感兴趣,请将 -Directory-File 传递给 Get-ChildItem
  • 如果您只需要简单的通配符过滤,请使用-Filter 而不是Where-Object(别名?)。 -Filter 速度更快,因为它使用在较低 API 级别进行过滤的文件系统提供程序,从而避免了 PowerShell 开销。

关于powershell - 将选定目录中的文件添加到 7-zip 存档,同时在存档中保留相对目录结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72626454/

相关文章:

powershell - 功能中的IF不起作用(PowerShell)

windows - 替换或删除文件夹中所有文件的文件名中的某些字符

windows - Makefile 仅适用于 MSYS2 (WIndows) 上的相对路径

php - 无法在 Windows 中解压缩大型 Linux 压缩存档

azure - 在 Azure 自动化中解压缩 .7z 文件

linux - 尝试在笔记本电脑上安装 Fedora 时如何解决 System.OutOfMemoryException 问题?

powershell - powershell中的where对象

python - 在目录结构中向上移动

python - 如何在 Visual Studio 中使用 python 设置相对路径?

windows - 7-Zip 关闭匹配 *.* 的文件夹的递归