将空文件夹压缩为文件夹,而不是文件

时间:2019-03-29 10:24:10

标签: powershell compression system

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

  

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

您知道如何避免这种情况,我希望将空文件夹作为文件夹...这似乎很荒谬...

编辑:

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

1 个答案:

答案 0 :(得分:0)

对我来说,如果我添加对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文件中包含一个空文件夹就很好了。

相关问题