循环所有子文件夹,在 PowerShell 中压缩每个文件夹

问题描述 投票:0回答:1

我正在尝试将根文件夹(InputFolder)中的每个子文件夹压缩到另一个文件夹(OutputFolder)上

这就是我的文件夹结构:

    • 001
    • 002
    • 003
    • ...
    • 020
    • 021
    • ...
    • 095

每个文件夹包含的文件数量在 5.00015.000

之间

我尝试了下面的代码,但它没有执行,我不知道它是否会创建 zip 文件。

param
(
  # The input folder containing the files to zip
  [Parameter(Mandatory = $true)]
  [string] $InputFolder,

  # The output folder that will contain the zip files
  [Parameter(Mandatory = $true)]
  [string] $OutputFolder
)

#Set-Variable SET_SIZE -option Constant -value 10

$subfolders = Get-ChildItem $InputFolder -Recurse | 
Where-Object { $_.PSIsContainer }


ForEach ($s in $subfolders) {

  $path = $s  #$s variable contains each folder
  $path 
  Set-Location $path.FullName

  $fullpath = $path.FullName
  $pathName = $path.BaseName

  #Get all items 
  $items = Get-ChildItem

  #Verify that there are such items in this directory, catch errors
  if ( $(Try { Test-Path $items } 
   Catch { "Cannot find items in $fullpath. 
   Sub-folders will be processed afterwards. 
   ERROR: $_" >>  "$InputtFolder\OutputLog.txt"  }) ) {

    $newpath = $OutputFolder + "\" + $pathName
    $newpath
    # Create directory if it doesn't exsist
    if (!(Test-Path $newpath))
    {
        $newfld = New-Item -ItemType Directory 
          -Path $OutputFolder -Name $pathName
    }

    $src = $newfld.FullName

    #move items to newly-created folder
    Move-Item $items -destination $src 

    $dest = "$src.zip"
    "Compressing $src to $dest"  >>  "$InputFolder\OutputLog.txt"  

    #the following block zips the folder
    try{
        $zip = New-Object ICSharpCode.SharpZipLib.Zip.FastZip
        $zip.CreateZip($dest, $src, $true, ".*")
        Remove-Item $src -force -recurse
    }
    catch { 
        "Folder could not be compressed. Removal of $src ABORTED. 
        ERROR: $_" >> "$InputFolder/OutputLog.txt" 
    }
  }
}
powershell
1个回答
5
投票

试试这个,

function Compress-Subfolders
{
    param
    (
        [Parameter(Mandatory = $true)][string] $InputFolder,
        [Parameter(Mandatory = $true)][string] $OutputFolder
    )

    $subfolders = Get-ChildItem $InputFolder | Where-Object { $_.PSIsContainer }

    ForEach ($s in $subfolders) 
    {
        $path = $s
        $path
        Set-Location $path.FullName
        $fullpath = $path.FullName
        $pathName = $path.BaseName

        #Get all items 
        $items = Get-ChildItem

        $zipname = $path.name + ".zip"
        $zippath = Join-Path $outputfolder $zipname
        Compress-Archive -Path $items -DestinationPath $zippath
    }
}

用途:

Compress-Subfolders -InputFolder c:\your\input\path\ -OutputFolder c:\your\output\path\

输出文件夹必须存在(如果不存在,您可以更改上面的代码来检查并创建该文件夹)。

您可以将该函数复制并粘贴到脚本文件中的其余代码上方。

你好,罗尼

© www.soinside.com 2019 - 2024. All rights reserved.