【问题标题】:Compress empty folders as folders, not files将空文件夹压缩为文件夹,而不是文件
【发布时间】:2019-03-29 10:24:10
【问题描述】:

我使用 System.IO.Compression.FileSystem 在 powershell 脚本中压缩带有子文件夹的文件夹。 有些文件夹是空的,它会创建空文件而不是空文件夹。 我认为这是一个错误,但他们在documentation 中指定了它:

文件系统中的目录结构保存在 档案。如果目录为空,则创建一个空存档。采用 此方法重载以指定压缩级别以及是否 在存档中包含基本目录。

你知道如何避免这种情况吗,我想要空文件夹作为文件夹......这看起来很荒谬......

编辑:

$compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
[System.IO.Compression.ZipFile]::CreateFromDirectory($Source, $Target, $compressionLevel, $true)

【问题讨论】:

  • 嗯...我不确定我是否正确。如果你压缩一些东西——不管它是什么——它会产生一个归档文件,比如archive.zip。如果你压缩一个空文件夹,这个空文件夹最终会出现在这样一个存档文件中。您是否考虑过使用内置 cmdlet Compress-Archive
  • 能否请您提供一个关于您执行压缩的具体方式的 sn-p?它将帮助我们与您一起进行测试和故障排除。
  • @root 搞定了,我觉得没必要这么简单。

标签: powershell compression system


【解决方案1】:

对我来说,如果我添加对 System.IO.Compression.FileSystem.dll 的引用,它就可以正常工作:

Add-Type -Path 'C:\Windows\Microsoft.Net\assembly\GAC_MSIL\System.IO.Compression.FileSystem\v4.0_4.0.0.0__b77a5c561934e089\System.IO.Compression.FileSystem.dll'

# compress using just two parameters. 
# This will omit the source folder and gives you no option to set the CompressionLevel
[System.IO.Compression.ZipFile]::CreateFromDirectory("D:\Testzip", "D:\result.zip")

如果您还想包含源文件夹,请使用带有 4 个参数的函数:

[System.IO.Compression.ZipFile]::CreateFromDirectory("D:\Testzip", "D:\result.zip", "Fastest", $true)

CompressionLevel Enum

为了测试,我使用了一个文件夹结构,其中只有子文件夹 D:\Testzip\folder1\folder1-1 为空:

D:\TESTZIP
|   the only file in the root directory.txt
|
\---folder1
    +---folder1-1
    \---folder1-2
            just a single file here.txt

result.zip 文件随后包含空文件夹就好了..

【讨论】:

  • 这是一个很好的折衷方案,但我需要 Optimal 级别。否则文件太重。
  • @toscanelli 这就是我将链接添加到Compression Level 的原因。只需将"Fastest" 更改为"Optimal"
  • 啊,抱歉,我知道诀窍是降低压缩级别。我看到您手动添加参考。我添加了没有完整路径(Add-Type -Assembly System.IO.Compression.FileSystem),因为我不知道将在哪个操作系统上运行(Windows 肯定,但不知道版本......)。无论如何我都会尝试。
  • 这很好,但您可以将 AddType 简化为 Add-Type -AssemblyName System.IO.Compression.FileSystem
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-01
  • 2010-09-05
  • 2012-06-19
  • 1970-01-01
相关资源
最近更新 更多