如何使用给定的Compress-CompatibleArchive函数将根目录纳入Zip文件?
解决PowerShell压缩时根目录未包含在Zip文件中的问题
问题说明
使用PowerShell的Compress-CompatibleArchive函数时出现报错:Root directory is not included in the ZipFile,需修改函数逻辑,让生成的Zip文件包含源根目录。
修改思路与实现
核心问题是原函数大概率直接压缩目录内的内容,未将源目录本身作为Zip内的根节点。调整路径映射逻辑即可解决:
修改后的函数代码
function Compress-CompatibleArchive { param( [Parameter(Mandatory=$true)] [string]$Path, [Parameter(Mandatory=$true)] [string]$DestinationPath ) # 确保目标路径父目录存在 $destDir = Split-Path -Path $DestinationPath -Parent if (-not (Test-Path -Path $destDir)) { New-Item -ItemType Directory -Path $destDir | Out-Null } # 获取源目录对象及名称(作为Zip内的根目录) $sourceDir = Get-Item -Path $Path $rootDirName = $sourceDir.Name # 创建并操作Zip文件 $zip = [System.IO.Compression.ZipFile]::Open($DestinationPath, [System.IO.Compression.ZipArchiveMode]::Create) try { # 遍历源目录下所有内容 Get-ChildItem -Path $Path -Recurse | ForEach-Object { # 计算相对路径,拼接根目录名称作为Zip内的路径前缀 $relativePath = $_.FullName.Substring($sourceDir.FullName.Length).TrimStart('\', '/') $zipEntryPath = if ($relativePath) { Join-Path -Path $rootDirName -ChildPath $relativePath } else { $rootDirName } # 创建对应Zip条目 if ($_.PSIsContainer) { $null = $zip.CreateEntry("$zipEntryPath/") } else { $null = [System.IO.Compression.ZipFileExtensions]::CreateEntryFromFile($zip, $_.FullName, $zipEntryPath) } } } finally { $zip.Dispose() } }
关键修改点
- 提取源目录名称:通过
Get-Item获取源目录对象,取出其名称作为Zip内的根目录节点。 - 调整路径映射:将每个文件/子目录的相对路径前拼接源目录名称,确保所有内容都被包裹在根目录下。
- 处理空相对路径:针对源目录本身,直接用目录名称创建Zip条目,保证根目录被显式包含。
验证方式
执行修改后的函数测试:
Compress-CompatibleArchive -Path "C:\TestSourceDir" -DestinationPath "C:\TestArchive.zip"
解压生成的Zip文件,会看到根目录TestSourceDir被包含在内,而非直接解压出目录内的文件。
内容的提问来源于stack exchange,提问作者Royston
相关产品推荐
相关产品推荐

