2013-10-30 90 views
0

大家好!使用vbs複製並重命名最早的文件

我一直在挖掘.vb和.vbs。複製後重命名文件有一個小問題。從this(只是給信貸的信用到期:P)人我已經找到如何將文件複製到另一個文件夾,但我似乎沒有能夠重命名該文件。

所以我要複製的文件,並命名原始到execute.HMS

這是複製代碼:提前和親切的問候

Set objFSo = CreateObject("Scripting.FileSystemObject") 
Set objFolder = objFSO.GetFolder("F:\commandfolder") 

Set colFiles = objFolder.Files 

dtmOldestDate = Now 

For Each objFile in colFiles 
    If objFile.DateCreated < dtmOldestDate Then 
     dtmOldestDate = objFile.DateCreated 
     strOldestFile = objFile.Path 
    End If 
Next 

objFSO.CopyFile strOldestFile, "F:\commandfolder\Processed\" 

感謝,

戴夫

回答

0

這是我工作的解決方案(它的編輯在上下文中,但是如果需要,你會發現它:))

Set obj = CreateObject("Scripting.FileSystemObject") 
Set objFSo = CreateObject("Scripting.FileSystemObject") 
Set objFolder = objFSO.GetFolder("F:\commandfolder") 

Set colFiles = objFolder.Files 

dtmOldestDate = Now 

For Each objFile in colFiles 
    If objFile.DateCreated < dtmOldestDate Then 
     dtmOldestDate = objFile.DateCreated 
     strOldestFile = objFile.Path 
    End If 
Next 


objFSO.CopyFile strOldestFile, "F:\commandfolder\Processed\" 
obj.DeleteFile("F:\commandfolder\Action\execute.hms") 
objFSO.MoveFile strOldestFile, "F:\commandfolder\Action\execute.hms" 
0

基於this answer to a 'find' problem,我添加了代碼來移動文件通過使用fileMove方法:

Const csSrcF = "..\testdata\17806396" 
    Const csDstF = "..\testdata\17806396\dst\" 
    Dim goFS  : Set goFS = CreateObject("Scripting.FileSystemObject") 
    Dim oLstPng : Set oLstPng = Nothing 
    Dim oFile 
    For Each oFile In goFS.GetFolder(csSrcF).Files 
     If "png" = LCase(goFS.GetExtensionName(oFile.Name)) Then 
     If oLstPng Is Nothing Then 
      Set oLstPng = oFile ' the first could be the last 
     Else 
      If oLstPng.DateLastModified < oFile.DateLastModified Then 
       Set oLstPng = oFile 
      End If 
     End If 
     End If 
    Next 
    If oLstPng Is Nothing Then 
    WScript.Echo "no .png found" 
    Else 
    WScript.Echo "found", oLstPng.Name, oLstPng.DateLastModified 
    oLstPng.Move csDstF 
    If goFS.FileExists(goFS.BuildPath(csDstF, oLstPng.Name)) Then 
     WScript.Echo "Moved." 
    Else 
     WScript.Echo "Not moved." 
    End If 
    End If 
1

VBScript不提供文件的重命名方法。你必須使用MoveFile代替:

objFSO.CopyFile strOldestFile, "F:\commandfolder\Processed\" 
objFSO.MoveFile strOldestFile, objFSO.GetParentFolderName(strOldestFile) & "\execute.HMS" 

一個更好的選擇可能會被記住的文件對象,而不只是它的路徑,然後使用該對象的方法:

For Each objFile in colFiles 
    If objFile.DateCreated < dtmOldestDate Then 
     dtmOldestDate = objFile.DateCreated 
     Set oldestFile = objFile 
    End If 
Next 

oldestFile.Copy "F:\commandfolder\Processed\" oldestFile.Name = "execute.HMS"
+0

有一個File/Folder.Move方法:http://msdn.microsoft.com/en-us/library/kxtftw67 %28v = vs.84%29.aspx –

+1

@ Ekkehard.Horner我知道。但是,如果我正確理解OP,他想將文件複製到'F:\ commandfolder \ Processed',然後重命名源文件夾中的文件。 –

+0

當然,你是對的。 –