Page 1 of 1

Always run a script in command line (cscript vs wscript)

Posted: Fri Nov 15, 2024 8:59 am
by admin
I was tired of double clicking some script I wrote for the command line that had a loop with wscript.echo statements.
Every time it sent output, it would pop up a message box and wait to be closed to continue execution.
This code prevents this

Add the following Subs and Functions to your scripts

Code: Select all

function cscript
dim scriptName

 cscript = false
 scriptName = CreateObject("Scripting.FileSystemObject").GetFileName( wscript.FullName )
   if scriptName = "cscript.exe" then cscript = True
end function

sub scriptEnd
 wscript.Echo "Press [ENTER] to end" 
 wscript.StdIn.ReadLine
end sub

sub run_in_window
Dim objShell

 Set objShell = wscript.CreateObject("wscript.Shell")
 objShell.Run "cscript """ & wscript.ScriptFullName & """"
 Set objShell = Nothing
 wscript.quit
end sub
Start your script with the following:

Code: Select all

Option Explicit
if cscript = false then run_in_window
if you would like your script to pause to view output add the following after all code:

Code: Select all

scriptEnd
Working Demo
Cut and paste into a .vbs document and double click it!

Code: Select all

Option Explicit
if cscript = false then run_in_window

wscript.echo "We're in a command line!"
scriptEnd


function cscript
dim scriptName

  cscript = false
  scriptName = CreateObject("Scripting.FileSystemObject").GetFileName( wscript.FullName )
     if scriptName = "cscript.exe" then cscript = True
end function

sub scriptEnd
wscript.Echo "Press [ENTER] to end"
wscript.StdIn.ReadLine
end sub

sub run_in_window
Dim objShell

  Set objShell = wscript.CreateObject("wscript.Shell")
  objShell.Run "cscript """ & wscript.ScriptFullName & """"
  Set objShell = Nothing
  wscript.quit
end sub