我使用System.IO.Compression.FileSystem来压缩PowerShell脚本中包含子文件夹的文件夹。有些文件夹是空的,它会创建空文件而不是空文件夹。我认为这是一个错误,但他们在他们的documentation中指定它:
文件系统中的目录结构保留在存档中。如果目录为空,则会创建一个空存档。使用此方法重载指定压缩级别以及是否在归档中包含基目录。
你知道如何避免这种情况,我想把空文件夹作为文件夹......这看起来很荒谬......
编辑:
$compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal
[System.IO.Compression.ZipFile]::CreateFromDirectory($Source, $Target, $compressionLevel, $true)
对我来说,如果我添加对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)
为了测试,我使用了一个文件夹结构,其中只有子文件夹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
文件包含空文件夹就好了..