Powershell分裂在多个文件夹中的巨大文件夹

问题描述:

我有一个文件夹,其中包含许多巨大的文件。我想将这些文件分成3个文件夹。要求是获取主文件夹中的文件数量,然后将这些文件平均分配到3个子文件夹中。 示例 - 主文件夹有100个文件。当我运行powershell时,应该分别使用33,33和34文件创建3个子文件夹。 我们如何使用Powershell来做到这一点?Powershell分裂在多个文件夹中的巨大文件夹

我已经试过如下:

$FileCount = (Get-ChildItem C:\MainFolder).count 
Get-ChildItem C:\MainFolder -r | Foreach -Begin {$i = $j = 0} -Process { 
    if ($i++ % $FileCount -eq 0) { 
    $dest = "C:\Child$j" 
    md $dest 
    $j++ 
    } 
    Move-Item $_ $dest 
} 
+0

您将首先尝试自己的自我,并让我们知道您是否有问题以及如何解决问题。 'Get-ChildItem'会返回数组。计算元素会告诉你你有多少物品,你可以通过将这个物品除以3来检查你的物品,并将剩下的物品留给最后一个物品组。 – Matt

+0

我在试这个代码。它确实创建了一个子文件夹,但不移动任何文件。 $ FileCount =(Get-ChildItem C:\ MainFolder)。count Get-ChildItem C:\ MainFolder -r | FOREACH -BEGIN {$ I = $ J = 0} {-Process如果 ($ I ++%$ FileCount -eq 0){$ DEST = “C:\儿童$ J” MD $ DEST $ J ++ } Move-Item $ _ $ dest } – user3220846

这是超级快速和肮脏的,但它的工作。

#Get the collection of files 
$files = get-childitem "c:\MainFolder" 

#initialize a counter to 0 or 1 depending on if there is a 
#remainder after dividing the number of files by 3. 
if($files.count % 3 -eq 0){ 
    $counter = 0 
} else { 
    $counter = 1 
} 

#Iterate through the files 
Foreach($file in $files){ 

    #Determine which subdirectory to put the file in 
    If($counter -lt $files.count/3){ 
      $d = "Dir1" 
    } elseif($counter -ge $files.count/3 * 2){ 
      $d = "Dir3" 
    } else { 
     $d = "Dir2" 
    } 

    #Create the subdirectory if it doesn't exist 
    #You could just create the three subdirectories 
    #before the loop starts and skip this 
    if(-Not (test-path c:\Child\$d)){ 
     md c:\Child\$d 
    } 

    #Move the file and increment the counter 
    move-item $file.FullName -Destination c:\Child\$d 
    $counter ++ 
} 

我认为有可能不做计算和分配自己。该解决方案:

  • 列出所有文件
  • 添加了基于周期0,1,2,0,1,2,0,1,2每个文件
  • 群体他们入桶计数器属性在柜台上
  • 移动每个桶中的一个命令

有余地重写它在很多方面,使之更好,但这样可以节省做数学,处理不均匀分配,遍历文件和运动他们一次一个,很容易适应不同数量的团体。

$files = (gci -recurse).FullName 
$buckets = $files |% {$_ | Add-Member NoteProperty "B" ($i++ % 3) -PassThru} |group B 

$buckets.Name |% { 
    md "c:\temp$_" 
    Move-Item $buckets[$_].Group "c:\temp$_" 
} 

这是另一种解决方案。这一个帐户不存在的子文件夹。

# Number of groups to support 
$groupCount = 3 
$path = "D:\temp\testing" 
$files = Get-ChildItem $path -File 

For($fileIndex = 0; $fileIndex -lt $files.Count; $fileIndex++){ 
    $targetIndex = $fileIndex % $groupCount 
    $targetPath = Join-Path $path $targetIndex 
    If(!(Test-Path $targetPath -PathType Container)){[void](new-item -Path $path -name $targetIndex -Type Directory)} 
    $files[$fileIndex] | Move-Item -Destination $targetPath -Force 
} 

如果您需要将文件分成不同的组数高于3.使用$groupCount也能正常工作与switch逻辑将改变$groupCount别的东西,如果计数的大于500例如。

通过逐个文件循环。使用$fileIndex作为一个跟踪器,我们在我的案例中确定文件夹0,1或2,该文件将被放入。然后使用该值检查目标文件夹是否存在。是的,这个逻辑很容易放置在循环之外,但如果脚本运行时文件和文件夹发生更改,则可能会说它更具弹性。

确保文件夹存在,如果没有。然后移动那个项目。使用模运算符,就像在其他答案中一样,我们不必担心有多少文件在那里。让PowerShell做数学。