You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过管道将Get-ChildItem结果传入Compress-Archive生成多份压缩包?

解决PowerShell批量单独压缩文件夹的问题

你遇到的情况很常见——直接用管道把Get-ChildItem的结果传给Compress-Archive时,它会把所有匹配的文件夹打包进同一个压缩包,而不是为每个文件夹生成单独的zip。这是因为Compress-Archive默认会将所有输入的路径合并到一个目标压缩文件中,不会自动逐个处理。

要实现每个文件夹对应一个独立的压缩包,你需要用ForEach-Object来遍历每个文件夹,对每个单独执行压缩操作:

完整路径版(推荐,避免当前目录问题)

Get-ChildItem -Path c:\test -Name folder* -Directory | ForEach-Object {
    Compress-Archive -Path "c:\test\$_" -DestinationPath "c:\test\$_.zip" -Verbose
}

当前目录简化版(如果已经切换到c:\test目录)

Set-Location c:\test
Get-ChildItem -Name folder* -Directory | ForEach-Object {
    Compress-Archive -Path $_ -DestinationPath "$_.zip" -Verbose
}

额外优化:覆盖已存在的压缩包

如果目标路径已经有同名的zip文件,默认会报错。可以加上-Force参数强制覆盖:

Get-ChildItem -Path c:\test -Name folder* -Directory | ForEach-Object {
    Compress-Archive -Path "c:\test\$_" -DestinationPath "c:\test\$_.zip" -Verbose -Force
}

这样执行后,c:\test目录下就会生成folder1.zip、folder2.zip和folder3.zip三个独立的压缩包,每个包里只包含对应文件夹的内容。

内容的提问来源于stack exchange,提问作者user736893

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 07:28:06