Question

I need to get all the files in a folder that match a certain wildcard pattern, using JScript. For example:

var fso = new ActiveXObject("Scripting.FileSystemObject");
var folderName = "C:\\TRScanFolder\\";
var folder = fso.GetFolder(folderName);
var searchPattern = "1001-*POD*.*"
// Now I need a list of all files matching the search pattern

I know I could iterate through the folder.Files collection and test the names against a regex, but I would prefer to just get Windows to do a search and get only the ones matching. This is mostly for performance, since there could be several hundred files in the folder, but only a few will be the ones I want.

Is there a function or something that I can use to do a search? Or should I stick with a loop and regex?

Edit: Here I what I got to work with a regex. Is there a way to do it without?

var regex = /^1001-.*POD.*\..*$/i;
var files = new Enumerator(folder.Files);
for (files.moveFirst(); !files.atEnd(); files.moveNext())
{
    var fileAttachment = files.item();
    if (regex.test(fileAttachment.Name))
    {
        // Do stuff
    }
}
Était-ce utile?

La solution

One alternative is to shell out to the command line and use the dir command.

var wsh = new ActiveXObject("WScript.Shell");
var fso = new ActiveXObject("Scripting.FileSystemObject");
var dirName = "C:\\someFolder";
var pattern = "s*";
var fileName;

var oExec = wsh.Exec('%comspec% /c dir /on /b "' + dirName + '\\' + pattern + '"');

// wait for dir command to finish
while (oExec.Status === 0) {
    WScript.Sleep(100);
}

// process output
while (!oExec.StdOut.AtEndOfStream) {
    fileName = oExec.StdOut.ReadLine();

    if ( fso.FileExists(fso.BuildPath(dirName, fileName)) ) {
        //do stuff
        WScript.Echo(fileName);
    }
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top