Print out files in a directory sorted by FileName

2020-05-06 14:05发布

问题:

I'm trying to print documents in a directory, ordered by file name ascending. I have the script below to print out the documents, which works, but it's in a random order. Is there any way to sort the "files" collection based on name?

'Set the TargetFolder
TargetFolder = "C:\Temp\Hewitt\TestPrintFolder" 

Set shellApplication = CreateObject("Shell.Application") 
Set folder = shellApplication.Namespace(TargetFolder) 
Set files = folder.Items 
For Each file In files 
    file.InvokeVerbEx ("Print") 
Next

回答1:

The are many ways to get an odered list of the file(name)s in a directory. One uses the .NET ArrayList - like this:

Option Explicit

Dim oFS    : Set oFS    = CreateObject("Scripting.FileSystemObject")
Dim sDir   : sDir       = "... your folder ..."
Dim oFiles : Set oFiles = CreateObject("System.Collections.ArrayList")
Dim oFile
For Each oFile In oFS.GetFolder(sDir).Files
    WScript.Echo oFile.Name
    oFiles.Add  oFile.Path
Next
WScript.Echo "----------"
oFiles.Sort
Dim sFile
For Each sFile In oFiles
    WScript.Echo oFS.GetFile(sFile).Name
Next

If you can't harness .Net, you could

  1. store the names in a VBScript array and find/write a Sort Sub/Function
  2. use a disconnected ADODB recordset
  3. shell out to dir /o:n


标签: vbscript