I was helping out in the MSN Groups scripting forum recently. The admin needed to find the latest file or most recently modified file in a folder. That sounded reasonable to me so I put together a function and short script that uses it. I thought I'd share it here:
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
'GetLatestFile.vbs
strDir="S:"
WScript.Echo "The newest file is " & GetLatestFile(strDir)
Function GetLatestFile(strDir)
'Returns the full path and file name of the file that
'was most recently modified. This function will Not
'recurse through subdirectories.
On Error Resume Next
Set objFSO=CreateObject("Scripting.FileSystemObject")
If objFSO.FolderExists(strDir) Then
Set objFldr=objFSO.GetFolder(strDir)
Set colFiles=objFldr.Files
strLatest=""
dtLatest="01/01/1900 12:00:00 AM"
For Each file In colFiles
If CDate(file.DateLastModified) > CDate(dtLatest) Then
strLatest=file.path
dtLatest=file.DateLastModified
End If
Next
GetLatestFile=strLatest
Else
GetLatestFile="Directory Not Found"
End If
End Function
The real "trick" to the script is to convert the DateLastModified property to a Date using CDate. Otherwise, the script tries to compare strings and you get some pretty weird and unexpected results. As written, this function will not recurse through subdirectories. Although you could make that modification. It also searches all file types. If you wanted to be more restrictive, say find the last Word document, you could either parse out the extension from the filename and only check .DOC or you could check the Type property of the file. This property will be something like "Microsoft Office Word 97 - 2003 Document".
You could also modify this function to return all files that had been modified since a certain date. Here's one possible modification:
dtCutOff="02/15/2007 12:00:00 AM"
For Each file In colFiles
If CDate(file.DateLastModified) > CDate(dtCutoff) Then
strLatest=strLatest & "," & file.path
End If
Next
'strip off leading comma
strLatest=Mid(strLatest,2)
GetLatestFile=strLatest
Now you'll get a comma separated list of all files that have been modified since 2/15/2007.
So kick it around. If you come up with some tweaks, post a comment.
Powershell Version:
(ls | sort creationtime -desc)[0]
Thank you!
—
Vinicius Canto
MVP Visual Developer – Scripting
MCP Windows 2000 Server, Windows XP e SQL Server 2000
Blog sobre scripting: http://viniciuscanto.blogspot.com
So many things like this are much easier in PowerShell. Which in fact was my first inclination. But since he had a larger VBScript he was working on that’s what I had to work with. But it is very apparent that you can get much more done with less code in PowerShell than VBScript.
Thanks for the tip.