批处理文件以使用Windows本机工具分别压缩子目录

时间:2018-12-21 14:11:14

标签: windows powershell batch-file command-prompt

我已经看到这个问题的答案,但是通常使用7zip之类的东西。我试图找到一种解决方案,该解决方案可以与Windows附带的功能结合使用,而无需任何其他工具。

我有一个包含数百个子目录的目录。我需要分别压缩每个子目录...。因此,我将获得数百个zip文件,每个子目录一个。这是在工作的计算机上,我没有管理权限来安装新软件...因此想要远离7zip,winRar等。

如果这已经在其他地方得到回答,我表示歉意...

2 个答案:

答案 0 :(得分:3)

我从来没有尝试过,但是有Compress-Archive

  

Compress-Archive cmdlet从一个或多个指定的文件或文件夹创建压缩(或压缩)存档文件。存档文件允许将多个文件打包并压缩为单个压缩文件,以便更轻松地分发和存储。可以使用CompressionLevel参数指定的压缩算法来压缩存档文件。

     

由于Compress-Archive依赖于Microsoft .NET Framework API System.IO.Compression.ZipArchive来压缩文件,因此当前可以通过使用Compress-Archive压缩的最大文件大小为2 GB。这是基础API的局限性。

这是我一起破解的示例脚本:

# configure as needed
$source = "c:\temp"
$target = "d:\temp\test"

# grab source file names and list them
$files = gci $source -recurse
$files

# target exists?
if( -not (test-path $target)) {
    new-item  $target  -type directory  
}

# compress, I am using -force here to overwrite existing files
$files | foreach{
    $dest = "$target\" + $_.name + ".zip"
    compress-archive  $_  $dest  -CompressionLevel Optimal  -force
}

# list target dir contents
gci $target -recurse

关于子文件夹,您可能需要对其进行一些改进。在以上版本中,子文件夹作为一个整体压缩为单个文件。这可能不完全是您想要的。

答案 1 :(得分:2)

Get-ChildItem c:\path\of\your\folder | ForEach-Object {
    $path = $_.FullName
    Compress-Archive -Path $path -DestinationPath "$path.zip"
}

我把它作为一个简短的摘要。如果这不符合您的要求,请立即发表评论。 在文件夹X中,有子文件夹Y1,Y2 ...

将创建Y1.zip,Y2.zip...。