locked
WMI Searching for files by Extension (javascript) Doesn't find any files RRS feed

  • Question

  • I have several files that are mp3s on my system.  I wrote some code that looks for mp3s by their extensions using WMI.  The snippet of code looks like this:

    var locator = new ActiveXObject("WbemScripting.SWbemLocator");
    var WMIService = locator.ConnectServer(".", "root/cimv2");
    var results = WMIService.ExecQuery("SELECT * FROM CIM_DataFile WHERE Extension='mp3'");
    var files = new Enumerator(results);
    
    for (; files.atEnd(); files.moveNext()) {
       var file = files.Item();
       console.log("File: " + file.Name);
    }
       

    There is no output.

    However, if I write the same code in Visual Basic, I get a full list of mp3s.  I did notice once when I had a break at the section of the Enumerator, that the result, took a while to get a Count of 3233, but if I remove the break, it ends up with no results again.


    Friday, January 8, 2016 9:42 AM

Answers

  • Your error is in this line:


    for (; files.atEnd(); files.moveNext()) {
    

    Your test statement, files.atEnd(), returns false, so therefore the loop terminates without executing anything in it. Invert the logic:


    for (; ! files.atEnd(); files.moveNext()) {
    


    -- Bill Stewart [Bill_Stewart]

    • Proposed as answer by Bill_Stewart Monday, January 11, 2016 3:10 PM
    • Marked as answer by Bill_Stewart Tuesday, March 1, 2016 10:46 PM
    Friday, January 8, 2016 3:24 PM

All replies

  • var locator = new ActiveXObject("WbemScripting.SWbemLocator");
    var WMIService = locator.ConnectServer(".", "root/cimv2");
    var results = WMIService.ExecQuery("SELECT * FROM CIM_DataFile WHERE Extension='mp3'");
    var fc = new Enumerator(results);
    for (fc.moveFirst(); !fc.atEnd(); fc.moveNext()){
    	var file = fc.item();
     	 WScript.Echo("File: " + file.Caption);
    }
    


    \_(ツ)_/

    Friday, January 8, 2016 2:35 PM
  • Your error is in this line:


    for (; files.atEnd(); files.moveNext()) {
    

    Your test statement, files.atEnd(), returns false, so therefore the loop terminates without executing anything in it. Invert the logic:


    for (; ! files.atEnd(); files.moveNext()) {
    


    -- Bill Stewart [Bill_Stewart]

    • Proposed as answer by Bill_Stewart Monday, January 11, 2016 3:10 PM
    • Marked as answer by Bill_Stewart Tuesday, March 1, 2016 10:46 PM
    Friday, January 8, 2016 3:24 PM