Search code examples
jscriptwsh

WSH/Javascript: how to access collection items


I am writing a JavaScript that shall be executed in Windows Scripting Host on the command line with cscript.exe. I need JSON parsing, so I decided on JavaScript instead of VBScript.

Now I am trying to access all files in a folder. Creating a folder object and getting a collection of files seem to work, but I cannot acccess the items in the collection.

My code looks like this:

var folder = fso.GetFolder("mypath");
WScript.Echo( "folder=" + folder.Path + " " + folder.Size );
var files = folder.Files;
WScript.Echo( "(files==null)=" + (files==null)); // returns false
WScript.Echo( "typeof files= " + typeof files ); // returns object
WScript.Echo( "files.Count=" + files.Count );    // returns the correct number of files
WScript.echo( typeof files[0] );                 // returns undefined
WScript.echo( typeof files.Item(0) );            // Invalid procedure call or argument
WScript.echo( typeof files(0) );                 // Invalid procedure call or argument
for( var file in files ) { }                     // Loop is not executed

According to the documentation folder.Files should return a collection. This seems to work, at least I can call files.Count and it returns the correct number of files. However my attempts to then access the items all fail. files[index] returns undefined, and the methods described in the documentation, files.Item(index) or files(index), result in runtime errors. If I try to loop through the collection, the loop is not executed.

Does anyone have a hint on how I can access the items in the files collection?


Solution

  • With Enumerator Object, you can iterate over the files in WSH JScript

    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var folder = fso.GetFolder("d:\\Projects\\EVCC Garmin\\evcc\\icons");
    WScript.Echo("folder=" + folder.Path + " " + folder.Size);
    
    var files = folder.Files;
    WScript.Echo("(files==null)=" + (files == null)); // returns false
    WScript.Echo("typeof files= " + typeof files); // returns object
    WScript.Echo("files.Count=" + files.Count); // returns the correct number of files
    
    
    const fileEnumerator = new Enumerator(files);
    for (; !fileEnumerator.atEnd(); fileEnumerator.moveNext()) {
        var file = fileEnumerator.item();
        WScript.Echo("File name: " + file.Name);
    }
    

    The Enumerator Object, will provide these functions for helping the iteration.

    1. .atEnd() check if we are at the end of the collection.
    2. .moveNext() to go to the next item in the collection.
    3. .item() get the current item.