Rob van der Woude's Scripting Pages

VBScript Scripting Techniques > Scripting Engine > Force a script to run in CSCRIPT

Force a script to run in CSCRIPT

 

There are several valid reasons to demand that a script runs in CSCRIPT instead of WSCRIPT, like for example to allow the use of Standard Input or to prevent a separate popup for each WScript.Echo line.

The following code can be copied and pasted at the top of your own scripts to force them to run in CSCRIPT:

Dim strArgs, strCmd, strEngine, i, objDebug, wshShell

Set wshShell = CreateObject( "WScript.Shell" )

strEngine = UCase( Right( WScript.FullName, 12 ) )

If strEngine <> "\CSCRIPT.EXE" Then
	' Recreate the list of command line arguments
	strArgs = ""
	If WScript.Arguments.Count > 0 Then
		For i = 0 To WScript.Arguments.Count - 1
			strArgs = strArgs & " " & WScript.Arguments(i)
		Next
	End If

	' Create the complete command line to rerun this script in CSCRIPT
	strCmd = "CSCRIPT.EXE //NoLogo """ & WScript.ScriptFullName & """" & strArgs

	' Rerun the script in CSCRIPT
	Set objDebug = wshShell.Exec( strCmd )

	' Wait until the script exits
	Do While objDebug.Status = 0
		WScript.Sleep 100
	Loop

	' Exit with CSCRIPT's return code
	WScript.Quit objDebug.ExitCode
End If

The code may look more complicated than necessary, that's because it returns CSCRIPT's return code to the WSCRIPT engine, just in case this return code is monitored by the program that started the script in WSCRIPT.

In case you want to force a script to run in WSCRIPT instead, just substitute WSCRIPT.EXE for CSCRIPT.EXE.

Thanks to Howard Bayne who corrected an error in the code (I had forgotten to subtract 1 from the WScript.Arguments.Count in the loop, causing an out-of-range error).


page last uploaded: 2017-09-29, 08:30