2015-11-20 128 views
0

我有一個文件夾,其中包含許多巨大的文件。我想將這些文件分成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

回答

1

這是超級快速和骯髒的,但它的工作。

#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 ++ 
} 
1

我認爲有可能不做計算和分配自己。該解決方案:

  • 列出所有文件
  • 添加了基於週期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$_" 
} 
0

這是另一種解決方案。這一個帳戶不存在的子文件夾。

# 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做數學。

相關問題