使用VBScript在单个文件夹中查找最近的文件日期

时间:2012-02-09 03:47:36

标签: file-io vbscript wsh

如何修改此VBScript以仅返回最新文件的名称和上次修改日期?目前它返回过去24小时内修改的任何内容。我想只查找最新的文件。我从StackOverflow借用了这个,而不是VBScript向导。

option explicit  
dim fileSystem, folder, file
dim path   
path = "C:\test"  
Set fileSystem = CreateObject("Scripting.FileSystemObject") 
Set folder = fileSystem.GetFolder(path) 
for each file in folder.Files         
if file.DateLastModified > dateadd("h", -24, Now) then         
'whatever you want to do to process'         
WScript.Echo file.Name & " last modified at " & file.DateLastModified     
end if
next 

2 个答案:

答案 0 :(得分:13)

以下实现GetRecentFile(和GetRecentFolder)并包含示例用法:

Option Explicit  

Function GetRecentFile(path)
  Dim fso, file
  Set fso = CreateObject("Scripting.FileSystemObject")
  Set GetRecentFile = Nothing
  For Each file in fso.GetFolder(path).Files
    If GetRecentFile is Nothing Then
      Set GetRecentFile = file
    ElseIf file.DateLastModified > GetRecentFile.DateLastModified Then
      Set GetRecentFile = file
    End If
  Next
End Function

Function GetRecentFolder(path)
  Dim fso, folder
  Set fso = CreateObject("Scripting.FileSystemObject")
  Set GetRecentFolder = Nothing
  For Each folder in fso.GetFolder(path).SubFolders
    If GetRecentFolder is Nothing Then
      Set GetRecentFolder = folder
    ElseIf folder.DateLastModified > GetRecentFolder.DateLastModified Then
      Set GetRecentFolder = folder
    End If
  Next
End Function

Dim recentFile
Set recentFile = GetRecentFolder("C:\Temp")
If recentFile is Nothing Then
  WScript.Echo "No recent files found"
Else
  WScript.Echo "Recent file is " & recentFile.Name & " " & recentFile.DateLastModified
End If

答案 1 :(得分:0)

这对我有用!先前答案的细分版本。

Set GetRecentFile = Nothing
For Each objFile In objFolder.Files
    If GetRecentFile is Nothing then
        Set GetRecentFile = objFile
    ElseIf objFile.DateLastModified > GetRecentFile.DateLastModified then
        Set GetRecentFile = objFile
    End If
Next