VBScript:根据文件名中的字符串将文件移动到不同的文件夹(For Each 循环)

VBScript: Move files to different folders depending on string in file name (For Each loop)

原题:

我对 VBScript 很不熟练,但需要一个有效的解决方案来节省我手动选择和复制文件的大量时间: 我有一个包含数千个光栅文件的文件夹,其中包含某个区域的每日温度值,总共涵盖了 30 年的时间。 为了计算每月 30 或 31 个文件中的每月平均值(在地理空间数据程序中),我需要将它们复制到单独的文件夹中,例如。 G。将 2000 年 1 月 1 日至 31 日的文件(名为 tx_20000101、tx_20000102 等)放入名为 T_01_Jan_2000 的文件夹中,并相应地保存所有其他月份和年份。

所以我需要一个脚本,它在所有文件名中搜索不同的文本字符串 (YYYYMM) 并将匹配的文件移动到给定的文件夹中(对于每个搜索字符串一个单独的文件夹)。

如何使用 VBScript 实现这一点? 在论坛中找到的例子(主要是这个:),我到目前为止:

Option Explicit
Sub Dateien_verschieben()

Dim i
Dim FSO : Set fso = CreateObject("Scripting.FileSystemObject")
Dim Quelle : Set Quelle = FSO.GetFolder("C:\Users\…\Temperature")

Dim Ziel1 : Set Ziel1 = FSO.GetFolder("C:\Users\…\Temperature\T_01_Jan\T_01_Jan_2000")
Dim Ziel2 : Set Ziel2 = FSO.GetFolder("C:\Users\…\Temperature\T_02_Feb\T_02_Feb_2000")
…
Dim Ziel12 : Set Ziel12 = FSO.GetFolder("C:\Users\…\Temperature\T_12_Dez\T_12_Dez_2000")

Dim Str1, Str2, Str3, Str4, Str5, Str6, Str7, Str8, Str9, Str10, Str11, Str12

Str1 = "200001"
Str2 = "200002"
…
Str12 = "200012"
i = 0

For Each file in Quelle.files
x = fso.getbasename(file)
If instr(lcase(x), Str1) Then
    i = i+1
       If fso.fileexists(Ziel1 & "\" & file.name) Then
        fso.deletefile Ziel1 & "\" & file.name, True
       End If
    fso.movefile Quelle & "\" & file.name, Ziel1
ElseIf instr(lcase(x), Str12) Then 'I have omitted the other ElseIf statements here for reasons of clarity
    i = i+1
        If fso.fileexists(Ziel12 & "\" & file.name) Then
        fso.deletefile Ziel12 & "\" & file.name, True
        End If
    fso.movefile Quelle & "\" & file.name, Ziel12
End If
Next

If i>0 Then
wscript.echo i&" files moved to path " & vbcrlf & Quelle
wscript.quit()
End If

wscript.echo "No matches found"

End Sub

但是,我遇到了不同的错误,例如 800A0414 和 800A0046,并且没有按预期获得脚本 运行。 欢迎任何有关更正代码或更有效的脚本编写方式的建议。

已编辑问题:

有一个包含数千个包含特定区域每日温度值的 netCDF 文件的文件夹,总共涵盖 30 年的时间段,如何将它们按月移动到单独的文件夹中? 月份文件夹应包含相应年份的子文件夹。

因此文件名为tx_20000101.nctx_20000102.nc等,并且都在文件夹中温度。 现在,1 月的所有文件都应进入名为 T_01 的文件夹中,其中包含名为 T_01_1991T_01_1992 依此类推,相应地适用于所有其他月份和年份。

VBScript 如何实现?

解决方案(感谢@Les Ferch):

Move = True 'Set to False for Copy 
SrcDir = ".\Temperature" Set oFSO = CreateObject("Scripting.FileSystemObject") 
Set Source = oFSO.GetFolder(SrcDir) 
For Each File in Source.Files   
    FileName = Right(File,11)   
    YYYY = Mid(FileName,1,4)   
    MM = Mid(FileName,5,2)   
    MonthDir = SrcDir & "\T_" & MM & "\"   
    YearDir = MonthDir & "T_" & MM & "_" & YYYY & "\"   
    If Not oFSO.FolderExists(MonthDir) Then oFSO.CreateFolder(MonthDir)   
    If Not oFSO.FolderExists(YearDir) Then oFSO.CreateFolder(YearDir)   
    If Move Then oFSO.MoveFile(File),YearDir Else oFSO.CopyFile(File),YearDir
Next