2016-11-16 64 views
0

我正在開發一個腳本,將文件夾中的文件數量分爲四組。這些將被轉換爲四個批處理文件,但現在問題是儘可能均勻地分割它們。vbscript將文件分成四組

下面的腳本將有所作爲 - 如果我有一個將被4除以均數的Count,但如果我有一個奇數,則不會出現並且少於四次將會崩潰。您可以運行腳本,只需使用您自己的文件路徑替換「C:\ 1_SourceData \ Section_16 \」。如果您取消註釋「將剩餘部分添加到前面」部分,則會將任何額外的文件(例如奇數)傳送到第一批,但這不起作用。文件夾中的文件數量範圍從1到25.

任何幫助將不勝感激。

Option Explicit 
Dim fileList : Set fileList = GetFileList("C:\1_SourceData\Section_16\") 
Dim NumOfFiles : NumOfFiles = fileList.Count - 1 
Dim modNumber : modNumber = NumOfFiles/4 
Dim remainder : remainder = NumOfFiles Mod modNumber 

Dim string1 : string1 = "batch" & batchCounter 
Dim string2 : string2 = "" 

'Add remainder to front 
'Dim i : i = 0 
'For i = NumOfFiles - remainder To NumOfFiles 
' string2 = string2 & vbTab & fileList(i) & vbNewLine 
'Next 

Dim batchCounter : batchCounter = 1 
Dim file 
Dim j : j = 0 
For Each file In fileList 
string2 = string2 & vbTab & file & vbNewLine 
    j = j + 1 

If j Mod modNumber = 0 Then 
    WScript.Echo string1 & vbNewLine & string2 
    batchCounter = batchCounter + 1 
    string1 = "batch" & batchCounter 
    string2 = "" 
End If 
Next 

Public Function GetFileList(path) 
Dim objFSO : Set objFSO = CreateObject("Scripting.FileSystemObject") 
Dim fileList : Set fileList = CreateObject("System.Collections.ArrayList") 
Dim InfFolder : Set InfFolder = objFSO.GetFolder(path) 
Dim File 

For Each File In objFSO.GetFolder(path).Files 
    fileList.Add File 
    Next Set GetFileList = fileList 
End Function 

回答

2

問題是:.Files集合僅可通過For Each訪問。 '按數字分配'(認爲模數)需要額外的計數器。演示腳本:

Option Explicit 

ReDim a(3) ' 4 groups/collections 
Dim i 
For i = 0 To UBound(a) 
    Set a(i) = CreateObject("System.Collections.ArrayList") 
Next 
i = 0 
Dim f 
' fake a list of elms accessible via For Each only 
For Each f In Split("a b c d e f g h i j k l m n") 
    a(i Mod 4).Add f ' use Mod to determine the 'bucket' 
    i = i + 1 ' counter needed for Mod 
Next 
For i = 0 To UBound(a) 
    WScript.Echo i, Join(a(i).ToArray()) 
Next 

輸出:

cscript 40639293.vbs 
0 a e i m 
1 b f j n 
2 c g k 
3 d h l 
0

你可以以不同的組織你的循環。

有一些F文件應該分成B批次的X個文件。有兩種情況:

  1. F是B的整數倍,在這種情況下,X = F/B
  2. F不是B的整數倍,在這種情況下,X =(F/B)+ 1

因此,我們可以寫兩個循環,即(合)從1數到F:

Option Explicit 

Const BATCHES = 4 
Const PATH = "C:\1_SourceData\Section_16" 

Dim FSO : Set FSO = CreateObject("Scripting.FileSystemObject") 
Dim fileList : Set fileList = GetFileList(PATH) 
Dim b, i, f, x 

f = fileList.Count 
x = CInt(f/BATCHES) 
If x * BATCHES < f Then x = x + 1 

For b = 0 To BATCHES - 1 
    If (b * x < f) Then WScript.Echo "batch" & (b + 1) 
    For i = b * x To (b + 1) * x - 1 
     If (i < f) Then WScript.Echo vbTab & fileList(i) 
    Next 
Next 

Function GetFileList(path) 
    Dim file 
    Set GetFileList = CreateObject("System.Collections.ArrayList") 
    For Each file In FSO.GetFolder(path).Files 
     GetFileList.Add File 
    Next 
End Function