PowerShell使用函数创建Zip包时如何包含源根目录?
解决方案
问题出在ZipFile.CreateFromDirectory方法的最后一个参数includeBaseDirectory,你之前设置为$false,这会仅将目标文件夹内的内容添加到压缩包,不包含文件夹本身。只需将该参数改为$true,就能让压缩包包含testing文件夹及其所有内容。
另外,原函数的$Path参数定义为[String[]](字符串数组),但ZipFile.CreateFromDirectory仅支持压缩单个目录,建议将参数类型改为[String]避免歧义。
修改后的完整代码如下:
Add-Type -Assembly System.IO.Compression.FileSystem function Compress-CompatibleArchive { param ( [String] $Path, [String] $DestinationPath ) $zipfilename = $DestinationPath $sourcedir = $Path $compressionLevel = [System.IO.Compression.CompressionLevel]::Optimal # 将最后一个参数改为 $true,包含源目录本身 [System.IO.Compression.ZipFile]::CreateFromDirectory($sourcedir, $zipfilename, $compressionLevel, $true) } Export-ModuleMember -Function Compress-CompatibleArchive
执行命令和之前一致:
.\PublishPlugin.ps1 C:\Users\USER\OneDrive\Pictures\testing C:\Users\USER\OneDrive\Pictures\zipdest\1.zip
此时生成的1.zip会包含testing文件夹,打开压缩包就能看到该文件夹及其内部所有内容。
内容的提问来源于stack exchange,提问作者Royston
相关产品推荐
相关产品推荐

