Forcing a Specific Scripting Engine

I get a lot of questions asking for a simple way to force a script to run in either cscript.exe or wscript.exe–and there are several reasons why you might want to force the use of one engine over another. Cscript.exe is a good choice whenever you want to have a console output or mask passwords. It’s also the only scripting engine that allows you to work with standard input and output streams. Wscript.exe is a good choice whenever you want a script to run silently or without a window. In either case, you can write your code so that it forces the use of one or the other.

The code is pretty straightforward. Just make sure that your script begins with the code below and you’ll be off and running.

If LCase(Right(WScript.FullName, 11)) <> "cscript.exe" Then
    strPath = WScript.ScriptFullName
    strCommand = "%comspec% /k cscript " & Chr(34) & strPath & chr(34)
    CreateObject("WScript.Shell").Run(strCommand)
    WScript.Quit
End If

In this case, I’m forcing the use of Cscript.exe. I’m using the WScript.FullName property to return a string that contains the path to the currently running scripting engine. If this path does not contain the text “cscript.exe” then I force the script to launch itself with the proper scripting engine.

In the second line, the WScript.ScriptFullName property returns the path to the current script. In the next line, I build a DOS command that will launch the script with the proper engine. Notice that this line also contains a reference to cscript.exe. Finally, the script uses the WshShell object to execute the command I’ve built and then the original script exits.

For WScript.exe, you just need to change the two instances of cscript.exe to wscript.exe as shown below.

If LCase(Right(WScript.FullName, 11)) <> "wscript.exe" Then
    strPath = WScript.ScriptFullName
    strCommand = "%comspec% /k wscript " & Chr(34) & strPath & chr(34)
    CreateObject("WScript.Shell").Run(strCommand)
    WScript.Quit
End If

With this code in place, you can ensure that your script will always run in either Cscript.exe or Wscript.exe regardless of the current system default engine.

Tags

Like the read? Share it!

Leave a Reply

Contact

Wanna say hello?
Drop us a line!

You'll find us here

1 Microsoft Way,
Redmond,
WA 98052, United States