19

I saved this VBScript script to my local machine as c:\test.vbs:

WScript.StdOut.WriteLine "This is a test"

When I run it from the command line, I get this error:

---------------------------
Windows Script Host
---------------------------
Script: C:\test.vbs
Line:   1
Char:   1
Error:  The handle is invalid. 
Code:   80070006
Source:     (null)

---------------------------
OK   
---------------------------

I get this under Windows Vista (SP1) and Windows XP Pro (SP3).

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
JosephStyons
  • 57,317
  • 63
  • 160
  • 234

3 Answers3

40

This link may help you:

http://www.tech-archive.net/Archive/Scripting/microsoft.public.scripting.vbscript/2004-07/0979.html

It appears that the handle StdOut is only available when using a console host (cscript.exe) and not a windowed host (wscript.exe). If you want the code to work, you have to use cscript.exe to run it.

The post also describes how to change default behavior to run scripts with cscript and not wscript.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Scott M.
  • 7,313
  • 30
  • 39
11

As described by the article in the accepted answer, my script worked when I called it from the command prompt like this:

cscript test.vbs

You can also change the default script host, so that a call to cscript is not necessary every single time. After doing that, the original command works unmodified.

cscript //h:cscript //s 

You can restore the original behavior with:

cscript //h:wscript //s 

Thanks!!

JosephStyons
  • 57,317
  • 63
  • 160
  • 234
1

I submitted this solution in bug "cscript - print output on same line on console?" which I feel is related to this issue.

I use the following "log" function in my JavaScript to support either wscript or cscript environment. As you can see this function will write to standard output only if it can.

var ExampleApp = {
    // Log output to console if available.
    //      NOTE: Script file has to be executed using "cscript.exe" for this to work.
    log: function (text) {
        try {
            // Test if stdout is working.
            WScript.stdout.WriteLine(text);
            // stdout is working, reset this function to always output to stdout.
            this.log = function (text) { WScript.stdout.WriteLine(text); };
        } catch (er) {
            // stdout is not working, reset this function to do nothing.
            this.log = function () { };
        }
    },
    Main: function () {
        this.log("Hello world.");
        this.log("Life is good.");
    }
};

ExampleApp.Main();
Community
  • 1
  • 1
Michael Erickson
  • 4,217
  • 2
  • 23
  • 10
  • according to this http://stackoverflow.com/questions/4999364/try-catch-end-try-in-vbscript vbscript doesn't have try catch. are you able to set a variable depending on which case it is, in vbscript? – barlop Oct 26 '13 at 23:32