【问题标题】:Batch file to compress subdirectories individually with Windows native tools使用 Windows 本机工具单独压缩子目录的批处理文件
【发布时间】:2018-12-21 14:11:14
【问题描述】:

我已经看到了这个问题的各种答案,但通常使用 7zip 之类的东西。我正在尝试找到一种解决方案,该解决方案可以在没有任何其他工具的情况下使用 Windows 附带的功能。

我有一个包含数百个子目录的目录。我需要单独压缩每个子目录……所以我会得到数百个 zip 文件,每个子目录一个。这是在我没有安装新软件的管理权限的工作机器上...因此希望远离 7zip、winRar 等。

如果这已经在其他地方得到回答,我很抱歉......

【问题讨论】:

    标签: windows powershell batch-file command-prompt


    【解决方案1】:

    我自己从未尝试过,但有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
    

    当涉及到子文件夹时,您可能需要对其进行一些改进。在上述版本中,子文件夹被作为一个整体压缩成一个文件。这可能不是您想要的。

    【讨论】:

    • 作为一个几乎没有 Windows 脚本编写经验的人,如何将它嵌入到列出父目录内容并遍历所有子目录的脚本中?
    • 您提供的链接是指powershell 6.0,在左侧的那个页面上,您可以选择PSversion并查看是否支持该cmdlet - Compress-Archive 需要PSv5.0+
    • 认为我可能已经找到了循环部分 - stackoverflow.com/questions/18847145/… 会建议......
    【解决方案2】:
    Get-ChildItem c:\path\of\your\folder | ForEach-Object {
        $path = $_.FullName
        Compress-Archive -Path $path -DestinationPath "$path.zip"
    }
    

    我把这个作为一个快速的sn-p。如果这不符合您的要求,请随时发表评论。 在文件夹 X 中,有子文件夹 Y1、Y2...

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-27
      相关资源
      最近更新 更多