使用vbs复制并重命名最旧的文件

时间:2013-10-30 13:18:24

标签: vbscript

再次大家好!

我一直在深入研究.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\"

提前致谢并亲切问候,

戴夫

3 个答案:

答案 0 :(得分: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"

答案 1 :(得分:0)

根据this answer to a 'find' problem,我添加了使用file的{​​{3}}方法移动文件的代码:

  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

答案 2 :(得分: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"