findstr() Runtime error 23 when called as a subprocess? - vb6

I am attempting to run findstr command from within my vb6 project however it seems that I am in over my head in determining the correct syntax.
I was calling a batch file to run the findstr but trying to integrate it in the project is failing.
'''''''' Lines below allow ONLY Numeric text in teh Test1 box
Dim textval As String
Dim numval As String
Private Sub Text1_Change()
textval = Text1.Text
If IsNumeric(textval) Then
numval = textval
Else
Text1.Text = CStr(numval)
End If
End Sub
'''''''' Lines above allow ONLY Numeric text in teh Test1 box
Private Sub Command1_Click()
''''Lines below enables program/project to execute in the current `enter code here`directory
Dim MyCurrentDir As String
'Show current directory
MyCurrentDir = CurDir
' MsgBox "Current Directory is " & MyCurrentDir
''''Lines above enables program/project to execute in the current directory
' Remarked for testing below WORKS: Shell (MyCurrentDir & "\findstring.bat " & Text1)
' TEST BELOW
Dim command As String
'findstr "%1" *achineCont*.log | findstr "Q_OUTFEED_EJECTBAG_SIG">FOUNDBAG.txt
command = "findstr "" & Text1 & "" *achineCont*.log | findstr ""Q_OUTFEED_EJECTBAG_SIG"">FOUNDBAG.txt"
Shell "cmd.exe /c command"
'findstr "Done" *ai*.log | findstr "writing" | findstr "%1">>FOUNDBAG.txt
Command2 = "Done"" *ai*.log | findstr ""writing"" | findstr "" & Text1 & "">>FOUNDBAG.txt"
Shell "cmd.exe /c command2"
'start "" cmd /c cscript ReadTimeFromFileWriteToNewFile.vbs
Command3 = "start """" cmd /c cscript ReadNewFile.vbs"
Shell "cmd.exe /c command3"
' TEST ABOVE
End Sub
Private Sub Command2_Click()
Unload Form1 'tell the form to unload
Set Form1 = Nothing 'free the memory used by the variables
End Sub
Private Sub Form_Load()
''''Lines below enables program/project to execute in the current directory
Dim MyCurrentDir As String
'Show current directory
MyCurrentDir = CurDir
' MsgBox "Current Directory is " & MyCurrentDir
''''Lines above enables program/project to execute in the current directory
End Sub

You are several quotes away from being correct in each command. You need to triple up some of the quotes, and re-position some of the others. For the first command, try this:
Command = "findstr """ & Text1 & """ *achineCont*.log | findstr ""Q_OUTFEED_EJECTBAG_SIG"">FOUNDBAG.txt"
For the second command, try this:
Command2 = """Done"" *ai*.log | findstr ""writing"" | findstr """ & Text1 & """>>FOUNDBAG.txt"
And last but not least, for the fourth command, try this:
Command4 = "findstr ""Done"" *ai*.log | findstr ""writing"" | findstr """ & Text1 & """>>FOUNDBAG.txt"
A good way to figure these out is to display the string with either Debug.Print or a MsgBox and adjust quotes until the string is correct. Also, remember a string has opening and closing quotes. Any other quotes within the string need to be escaped by doubling up the quote.

Related

Vbs print to console [duplicate]

What is the command or the quickest way to output results to console using vbscript?
You mean:
Wscript.Echo "Like this?"
If you run that under wscript.exe (the default handler for the .vbs extension, so what you'll get if you double-click the script) you'll get a "MessageBox" dialog with your text in it. If you run that under cscript.exe you'll get output in your console window.
This was found on Dragon-IT Scripts and Code Repository.
You can do this with the following and stay away from the cscript/wscript differences and allows you to get the same console output that a batch file would have. This can help if your calling VBS from a batch file and need to make it look seamless.
Set fso = CreateObject ("Scripting.FileSystemObject")
Set stdout = fso.GetStandardStream (1)
Set stderr = fso.GetStandardStream (2)
stdout.WriteLine "This will go to standard output."
stderr.WriteLine "This will go to error output."
You only need to force cscript instead wscript. I always use this template. The function ForceConsole() will execute your vbs into cscript, also you have nice alias to print and scan text.
Set oWSH = CreateObject("WScript.Shell")
vbsInterpreter = "cscript.exe"
Call ForceConsole()
Function printf(txt)
WScript.StdOut.WriteLine txt
End Function
Function printl(txt)
WScript.StdOut.Write txt
End Function
Function scanf()
scanf = LCase(WScript.StdIn.ReadLine)
End Function
Function wait(n)
WScript.Sleep Int(n * 1000)
End Function
Function ForceConsole()
If InStr(LCase(WScript.FullName), vbsInterpreter) = 0 Then
oWSH.Run vbsInterpreter & " //NoLogo " & Chr(34) & WScript.ScriptFullName & Chr(34)
WScript.Quit
End If
End Function
Function cls()
For i = 1 To 50
printf ""
Next
End Function
printf " _____ _ _ _____ _ _____ _ _ "
printf "| _ |_| |_ ___ ___| |_ _ _ _| | | __|___ ___|_|___| |_ "
printf "| | | '_| . | | --| | | | . | |__ | _| _| | . | _|"
printf "|__|__|_|_,_|___|_|_|_____|_____|___| |_____|___|_| |_| _|_| "
printf " |_| v1.0"
printl " Enter your name:"
MyVar = scanf
cls
printf "Your name is: " & MyVar
wait(5)
There are five ways to output text to the console:
Dim StdOut : Set StdOut = CreateObject("Scripting.FileSystemObject").GetStandardStream(1)
WScript.Echo "Hello"
WScript.StdOut.Write "Hello"
WScript.StdOut.WriteLine "Hello"
Stdout.WriteLine "Hello"
Stdout.Write "Hello"
WScript.Echo will output to console but only if the script is started using cscript.exe. It will output to message boxes if started using wscript.exe.
WScript.StdOut.Write and WScript.StdOut.WriteLine will always output to console.
StdOut.Write and StdOut.WriteLine will also always output to console. It requires extra object creation but it is about 10% faster than WScript.Echo.
I came across this post and went back to an approach that I used some time ago which is similar to #MadAntrax's.
The main difference is that it uses a VBScript user-defined class to wrap all the logic for switching to CScript and outputting text to the console, so it makes the main script a bit cleaner.
This assumes that your objective is to stream output to the console, rather than having output go to message boxes.
The cCONSOLE class is below. To use it, include the complete class at the end of your script, and then instantiate it right at the beginning of the script. Here is an example:
Option Explicit
'// Instantiate the console object, this automatically switches to CSCript if required
Dim CONS: Set CONS = New cCONSOLE
'// Now we can use the Consol object to write to and read from the console
With CONS
'// Simply write a line
.print "CSCRIPT Console demo script"
'// Arguments are passed through correctly, if present
.Print "Arg count=" & wscript.arguments.count
'// List all the arguments on the console log
dim ix
for ix = 0 to wscript.arguments.count -1
.print "Arg(" & ix & ")=" & wscript.arguments(ix)
next
'// Prompt for some text from the user
dim sMsg : sMsg = .prompt( "Enter any text:" )
'// Write out the text in a box
.Box sMsg
'// Pause with the message "Hit enter to continue"
.Pause
End With
'= =========== End of script - the cCONSOLE class code follows here
Here is the code for the cCONSOLE class
CLASS cCONSOLE
'= =================================================================
'=
'= This class provides automatic switch to CScript and has methods
'= to write to and read from the CSCript console. It transparently
'= switches to CScript if the script has been started in WScript.
'=
'= =================================================================
Private oOUT
Private oIN
Private Sub Class_Initialize()
'= Run on creation of the cCONSOLE object, checks for cScript operation
'= Check to make sure we are running under CScript, if not restart
'= then run using CScript and terminate this instance.
dim oShell
set oShell = CreateObject("WScript.Shell")
If InStr( LCase( WScript.FullName ), "cscript.exe" ) = 0 Then
'= Not running under CSCRIPT
'= Get the arguments on the command line and build an argument list
dim ArgList, IX
ArgList = ""
For IX = 0 to wscript.arguments.count - 1
'= Add the argument to the list, enclosing it in quotes
argList = argList & " """ & wscript.arguments.item(IX) & """"
next
'= Now restart with CScript and terminate this instance
oShell.Run "cscript.exe //NoLogo """ & WScript.ScriptName & """ " & arglist
WScript.Quit
End If
'= Running under CScript so OK to continue
set oShell = Nothing
'= Save references to stdout and stdin for use with Print, Read and Prompt
set oOUT = WScript.StdOut
set oIN = WScript.StdIn
'= Print out the startup box
StartBox
BoxLine Wscript.ScriptName
BoxLine "Started at " & Now()
EndBox
End Sub
'= Utility methods for writing a box to the console with text in it
Public Sub StartBox()
Print " " & String(73, "_")
Print " |" & Space(73) & "|"
End Sub
Public Sub BoxLine(sText)
Print Left(" |" & Centre( sText, 74) , 75) & "|"
End Sub
Public Sub EndBox()
Print " |" & String(73, "_") & "|"
Print ""
End Sub
Public Sub Box(sMsg)
StartBox
BoxLine sMsg
EndBox
End Sub
'= END OF Box utility methods
'= Utility to center given text padded out to a certain width of text
'= assuming font is monospaced
Public Function Centre(sText, nWidth)
dim iLen
iLen = len(sText)
'= Check for overflow
if ilen > nwidth then Centre = sText : exit Function
'= Calculate padding either side
iLen = ( nWidth - iLen ) / 2
'= Generate text with padding
Centre = left( space(iLen) & sText & space(ilen), nWidth )
End Function
'= Method to write a line of text to the console
Public Sub Print( sText )
oOUT.WriteLine sText
End Sub
'= Method to prompt user input from the console with a message
Public Function Prompt( sText )
oOUT.Write sText
Prompt = Read()
End Function
'= Method to read input from the console with no prompting
Public Function Read()
Read = oIN.ReadLine
End Function
'= Method to provide wait for n seconds
Public Sub Wait(nSeconds)
WScript.Sleep nSeconds * 1000
End Sub
'= Method to pause for user to continue
Public Sub Pause
Prompt "Hit enter to continue..."
End Sub
END CLASS
Create a .vbs with the following code, which will open your main .vbs:
Set objShell = WScript.CreateObject("WScript.shell")
objShell.Run "cscript.exe ""C:\QuickTestb.vbs"""
Here is my main .vbs
Option Explicit
Dim i
for i = 1 To 5
Wscript.Echo i
Wscript.Sleep 5000
Next
You can run this script to echo in the command line
set wshShell = createObject("wscript.shell")
wshShell.run"cmd.exe /c echo something",1
For console output I use a snippet that quits elegantly if run in the wrong run-time. (And print is shorter to type...)
Sub print(s)
On Error Resume Next
WScript.stdout.WriteLine (s)
If err= &h80070006& Then WScript.Echo " Please run this script with CScript": WScript.quit
End Sub
print "hello"

How do I convert the weekday command so that I can manually pick the day for each task rather than it detecting it automatically?

When I started on this I wasn't aware that I had to be able to select each daily task manually and pick each task whenever I want, I'm trying to figure out how to convert it into a manual entry so I don't have to rework the whole thing, bear in mind I'm very new to vbscript so if there's an obvious solution I apologize. I'm still working on the later days of the week to finish this.
dtmToday = Date()
dtmDayOfWeek = DatePart("w", dtmToday)
'Select case to pickup the value of day of the week and call procedure
Select Case dtmDayOfWeek
Case 1
Call Sunday()
Case 2
Call Monday()
Case 3
Call Tuesday()
Case 4
Call Wednesday()
Case 5
Call Thursday()
Case 6
Call Friday()
Case 7
Call Saturday()
End Select
'Sunday procedure will execute from select case
sub Sunday()
'defining variables
dim wshShell
dim path
dim fso
'setting up the environment to run vbscript
Set fso = CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")
' Execute the command and append to the text file
WShShell.run "cmd /c ping -n 10 youtube.com >> ping.txt", hidden
wscript.quit
End sub
'Monday procedure will execute from select case
sub Monday()
'defining variables
dim wshShell
dim path
dim fso
'setting up the environment to run vbscript
Set fso = CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")
' to execute the command and append to the text file using >> if you want to text to be overriden use >
WShShell.run "cmd /c netstat >> netstat.txt", hidden
wscript.quit
End sub
'Tuesday procedure will execute from select case
sub Tuesday()
'defining variables
dim wshShell
dim path
dim fso
'setting up the environment to run vbscript
Set fso = CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")
' to execute the command and append to the text file using >> if you want to text to be overriden use >
WShShell.run "cmd /c arp -a >> arp.txt", hidden
wscript.quit
End sub
sub Wednesday()
'defining variables
dim wshShell
dim path
dim fso
'setting up the environment to run vbscript
Set fso = CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")
WShShell.run "cmd /c nbstat -n >> nbstat.txt", hidden
wscript.quit
End Sub
sub Thursday()
'defining variables
dim wshShell
dim path
dim fso
'setting up the environment to run vbscript
Set fso = CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")
WShShell.run "cmd /c tracert -n 10 youtube.com >> nbstat.txt", hidden
wscript.quit
End Sub
You need first optimize your code to avoid heavy duplication as #Lankymart was mentioned it in his comment, by writing one function and call it when you need it, and to store all your commands into an array for easy access by their index.
So your code can be written like that :
Option Explicit
' We define our Global variables
Dim Title,ArrCommands,strcmd,dtmDayOfWeek,IndexCommand,UserInput
Title = "Run command line based on the Day Of Week"
'----------------------------------------------------------------------------------
' We define and store our commands lines into an array
ArrCommands = Array(_
"ping -n 10 youtube.com >> ping.txt",_
"netstat >> netstat.txt",_
"arp -a >> arp.txt",_
"Color 0A & Title Running nbtstat command & nbtstat -n",_
"Color 0A & Title Running Tracert command & tracert youtube.com",_
"Color 0A & Title Running Ipconfig command & Ipconfig /all",_
"Color 0A & Title Running netstat command & netstat -ano"_
)
'-------------------------------Main Program---------------------------------------
Do While Not IsDate(UserInput)
UserInput = InputBox("Type a date here example 24/06/2020",Title,"24/06/2020")
dtmDayOfWeek = MyWeekday(UserInput)
IndexCommand = dtmDayOfWeek - 1
Loop
MsgBox "Day of the Week = "& dtmDayOfWeek & vbCrlf &_
"The command will be executed is : "& ArrCommands(IndexCommand),vbInformation,Title
'Select case to pickup the value of day of the week
Select Case dtmDayOfWeek
Case 1
Call Execute(ArrCommands(IndexCommand),0)
Case 2
Call Execute(ArrCommands(IndexCommand),0)
Case 3
Call Execute(ArrCommands(IndexCommand),0)
Case 4
Call Execute(ArrCommands(IndexCommand),1)
Case 5
Call Execute(ArrCommands(IndexCommand),1)
Case 6
Call Execute(ArrCommands(IndexCommand),1)
Case 7
Call Execute(ArrCommands(IndexCommand),1)
End Select
'MsgBox "Command line is done",vbInformation,Title
'----------------------------------------------------------------------------------
Function MyWeekday(MyDate)
If MyDate = "" Then MyDate = Date()
If IsDate(MyDate) Then
MyWeekDay = Weekday(MyDate)
Exit Function
End If
End Function
'----------------------------------------------------------------------------------
Sub Execute(StrCmd,Console)
Dim ws,MyCmd
Set ws = CreateObject("wscript.Shell")
'The console = 0 means will be running in hidden mode
If Console = 0 Then
MyCmd = "CMD /C " & StrCmd & " "
ws.run MyCmd,Console,True
End If
'The console = 1 means will be running in not hidden mode
If Console = 1 Then
MyCmd = "CMD /K " & StrCmd & " "
ws.run MyCmd,Console,True
End If
End Sub
'----------------------------------------------------------------------------------

Getting "file not found" error

I don't understand why this code:
Set oWMP = CreateObject("WMPlayer.OCX.7")
Set oCMD = CreateObject("WScript.Shell")
Sub OpenFile(file)
oCMD.run file
End Sub
Sub OpenCMD
oCMD.run "%COMAPEC% /c start cmd"
End Sub
Sub Blink
oCMD.run "%COMAPEC% /c exit"
End Sub
Sub Wait(seconds)
oCMD.run "%COMSPEC% /c ping -n " & seconds+1 & " 127.0.0.1", 0, True
End Sub
Sub PromptCommand(command)
oCMD.run "%COMAPEC% /c " & command
End Sub
Blink
Wait("0.5")
OpenCMD
Wait("7")
OpenFile("C:\Documents and Settings\Scott\Desktop\Lemmings\LEMMINGS.bat")
gives me the following error:
With line 13 being
oCMD.run "%COMAPEC% /c exit"
I'd suspect that you simply mistyped the environment variable. Replace every occurrence of %COMAPEC% in your script with %COMSPEC%.
And, of course, always put paths between double quotes, as #Ekkehard.Horner recommended. You can simplify the handling by using a quoting function like this:
Function qq(str) : qq = Chr(34) & str & Chr(34) : End Function
oCMD.Run qq(file)
which is a bit better readable than a bunch of string concatenations.
Start with quoting the command line passed to .Run:
oCMD.run """" & file & """""
instead of:
oCMD.run file
(cf. this)

Passing Caret to command line using VBScript

Having a hard time figuring this one out. I have a vbscript that asks for username and password. Then the script runs PSExec.exe passing those to the command line like this.
strUser = Inputbox("Username:","Username")
strPassword = Inputbox("Password:","Password")
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "%comspec% /K psexec.exe \\workstation -u " & struser _
& " -p " & strPassword & " -d calc.exe", 1, false
This works fine if the password doesn't have a caret in it. BUT if it does have one, for example if the password is "Pass)(*&^%$##!" I get the following error from psexec.
'%$##!' is not recognized as an internal or external command,
operable program or batch file.
The caret is being read by the command line as a space so it thinks it's trying to run this command.
psexec.exe \\workstation64 -u User -p Pass)(*& %$##! -d Calc.exe
As you can see there is a space instead of a caret so psexec see's %$##! as the command.
I've seen an example for passing it when using a batch file but it doesn't work in this case. It said adding an extra ^ like this ^^ works in a bat file.
How can I pass a caret to the command line????
UPDATE......
I worked on this for about 45 minutes today at work and couldn't get it to work. First thing I tried was to add quotes to the password and it still didn't work. I just tested it here at the house and it worked fine....... OS at work is Windows XP and at home I run Windows 7. I will try again in the morning to make sure I didn't mistype something. Here is what I did to make it work at home on Windows 7.
strUser = Inputbox("Username:","Username")
strPassword = Inputbox("Password:","Password")
strPassword = chr(34) & strPassword & chr(34)
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "%comspec% /K psexec.exe \\workstation -u " & struser _
& " -p " & strPassword & " -d calc.exe", 1, false
The problem lays in using of ampersand, not caret: single ampersand is used as a command separator, so rest of the line after &-sign considered to be a next command by cmd interpreter.
In next example I have used SET command instead of PSExec, as I will not experiment with PSExec.
All goes well with SET command, even if escaped all characters:), but I'm not sure about percentage sign, which is said "must be doubled to use literally".
Dim strPssw: strPssw = "/Pass"")=(*&^%$##!"
Dim ii, strChar, strEscape
Dim strPassword: strPassword = ""
For ii = 1 To Len( strPssw) 'cannot use Replace() function
strChar = Mid( strPssw, ii, 1)
Select Case strChar
Case "&", """", "^", "%", "=", _
"#", "(", ")", "!", "*", "?", _
".", "\", "|", ">", "<", "/"
strEscape = "^"
Case Else
strEscape = "" 'all goes well even if strEscape = "^" here
End Select
strPassword = strPassword & strEscape & strChar
Next
Dim objShell: Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "%comspec% /C set varia=" & strPassword & "&set varia&pause&set varia=", 1, false
' # - At Symbol: be less verbose
' & - Single Ampersand: used as a command separator
' ^ - Caret: general escape character in batch
' " - Double Quote: surrounding a string in double quotes escapes all of the characters contained within it
' () - Parentheses: used to make "code blocks" of grouped commands
' % - Percentage Sign: are used to mark some variables, must be doubled to use literally
' ! - Exclamation Mark: to mark delayed expansion environment variables !variable!
' * - Asterisk: wildcard matches any number or any characters
' ? - Question Mark: matches any single character
' . - Single dot: represents the current directory
' \ - Backslash: represent the root directory of a drive dir ^\
' | - Single Pipe: redirects the std.output of one command into the std.input of another
' > - Single Greater Than: redirects output to either a file or file like device
' < - Less Than: redirect the contents of a file to the std.input of a command
''
' && - Double Ampersand: conditional command separator (if errorlevel 0)
' .. - Double dot: represents the parent directory of the current directory
' || - Double Pipe: conditional command separator (if errorlevel > 0)
' :: - Double Colon: alternative to "rem" for comments outside of code blocks
' >> - Double Greater than: output will be added to the very end of the file
' thanks to http://judago.webs.com/batchoperators.htm
'

vbscript output to console

What is the command or the quickest way to output results to console using vbscript?
You mean:
Wscript.Echo "Like this?"
If you run that under wscript.exe (the default handler for the .vbs extension, so what you'll get if you double-click the script) you'll get a "MessageBox" dialog with your text in it. If you run that under cscript.exe you'll get output in your console window.
This was found on Dragon-IT Scripts and Code Repository.
You can do this with the following and stay away from the cscript/wscript differences and allows you to get the same console output that a batch file would have. This can help if your calling VBS from a batch file and need to make it look seamless.
Set fso = CreateObject ("Scripting.FileSystemObject")
Set stdout = fso.GetStandardStream (1)
Set stderr = fso.GetStandardStream (2)
stdout.WriteLine "This will go to standard output."
stderr.WriteLine "This will go to error output."
You only need to force cscript instead wscript. I always use this template. The function ForceConsole() will execute your vbs into cscript, also you have nice alias to print and scan text.
Set oWSH = CreateObject("WScript.Shell")
vbsInterpreter = "cscript.exe"
Call ForceConsole()
Function printf(txt)
WScript.StdOut.WriteLine txt
End Function
Function printl(txt)
WScript.StdOut.Write txt
End Function
Function scanf()
scanf = LCase(WScript.StdIn.ReadLine)
End Function
Function wait(n)
WScript.Sleep Int(n * 1000)
End Function
Function ForceConsole()
If InStr(LCase(WScript.FullName), vbsInterpreter) = 0 Then
oWSH.Run vbsInterpreter & " //NoLogo " & Chr(34) & WScript.ScriptFullName & Chr(34)
WScript.Quit
End If
End Function
Function cls()
For i = 1 To 50
printf ""
Next
End Function
printf " _____ _ _ _____ _ _____ _ _ "
printf "| _ |_| |_ ___ ___| |_ _ _ _| | | __|___ ___|_|___| |_ "
printf "| | | '_| . | | --| | | | . | |__ | _| _| | . | _|"
printf "|__|__|_|_,_|___|_|_|_____|_____|___| |_____|___|_| |_| _|_| "
printf " |_| v1.0"
printl " Enter your name:"
MyVar = scanf
cls
printf "Your name is: " & MyVar
wait(5)
There are five ways to output text to the console:
Dim StdOut : Set StdOut = CreateObject("Scripting.FileSystemObject").GetStandardStream(1)
WScript.Echo "Hello"
WScript.StdOut.Write "Hello"
WScript.StdOut.WriteLine "Hello"
Stdout.WriteLine "Hello"
Stdout.Write "Hello"
WScript.Echo will output to console but only if the script is started using cscript.exe. It will output to message boxes if started using wscript.exe.
WScript.StdOut.Write and WScript.StdOut.WriteLine will always output to console.
StdOut.Write and StdOut.WriteLine will also always output to console. It requires extra object creation but it is about 10% faster than WScript.Echo.
I came across this post and went back to an approach that I used some time ago which is similar to #MadAntrax's.
The main difference is that it uses a VBScript user-defined class to wrap all the logic for switching to CScript and outputting text to the console, so it makes the main script a bit cleaner.
This assumes that your objective is to stream output to the console, rather than having output go to message boxes.
The cCONSOLE class is below. To use it, include the complete class at the end of your script, and then instantiate it right at the beginning of the script. Here is an example:
Option Explicit
'// Instantiate the console object, this automatically switches to CSCript if required
Dim CONS: Set CONS = New cCONSOLE
'// Now we can use the Consol object to write to and read from the console
With CONS
'// Simply write a line
.print "CSCRIPT Console demo script"
'// Arguments are passed through correctly, if present
.Print "Arg count=" & wscript.arguments.count
'// List all the arguments on the console log
dim ix
for ix = 0 to wscript.arguments.count -1
.print "Arg(" & ix & ")=" & wscript.arguments(ix)
next
'// Prompt for some text from the user
dim sMsg : sMsg = .prompt( "Enter any text:" )
'// Write out the text in a box
.Box sMsg
'// Pause with the message "Hit enter to continue"
.Pause
End With
'= =========== End of script - the cCONSOLE class code follows here
Here is the code for the cCONSOLE class
CLASS cCONSOLE
'= =================================================================
'=
'= This class provides automatic switch to CScript and has methods
'= to write to and read from the CSCript console. It transparently
'= switches to CScript if the script has been started in WScript.
'=
'= =================================================================
Private oOUT
Private oIN
Private Sub Class_Initialize()
'= Run on creation of the cCONSOLE object, checks for cScript operation
'= Check to make sure we are running under CScript, if not restart
'= then run using CScript and terminate this instance.
dim oShell
set oShell = CreateObject("WScript.Shell")
If InStr( LCase( WScript.FullName ), "cscript.exe" ) = 0 Then
'= Not running under CSCRIPT
'= Get the arguments on the command line and build an argument list
dim ArgList, IX
ArgList = ""
For IX = 0 to wscript.arguments.count - 1
'= Add the argument to the list, enclosing it in quotes
argList = argList & " """ & wscript.arguments.item(IX) & """"
next
'= Now restart with CScript and terminate this instance
oShell.Run "cscript.exe //NoLogo """ & WScript.ScriptName & """ " & arglist
WScript.Quit
End If
'= Running under CScript so OK to continue
set oShell = Nothing
'= Save references to stdout and stdin for use with Print, Read and Prompt
set oOUT = WScript.StdOut
set oIN = WScript.StdIn
'= Print out the startup box
StartBox
BoxLine Wscript.ScriptName
BoxLine "Started at " & Now()
EndBox
End Sub
'= Utility methods for writing a box to the console with text in it
Public Sub StartBox()
Print " " & String(73, "_")
Print " |" & Space(73) & "|"
End Sub
Public Sub BoxLine(sText)
Print Left(" |" & Centre( sText, 74) , 75) & "|"
End Sub
Public Sub EndBox()
Print " |" & String(73, "_") & "|"
Print ""
End Sub
Public Sub Box(sMsg)
StartBox
BoxLine sMsg
EndBox
End Sub
'= END OF Box utility methods
'= Utility to center given text padded out to a certain width of text
'= assuming font is monospaced
Public Function Centre(sText, nWidth)
dim iLen
iLen = len(sText)
'= Check for overflow
if ilen > nwidth then Centre = sText : exit Function
'= Calculate padding either side
iLen = ( nWidth - iLen ) / 2
'= Generate text with padding
Centre = left( space(iLen) & sText & space(ilen), nWidth )
End Function
'= Method to write a line of text to the console
Public Sub Print( sText )
oOUT.WriteLine sText
End Sub
'= Method to prompt user input from the console with a message
Public Function Prompt( sText )
oOUT.Write sText
Prompt = Read()
End Function
'= Method to read input from the console with no prompting
Public Function Read()
Read = oIN.ReadLine
End Function
'= Method to provide wait for n seconds
Public Sub Wait(nSeconds)
WScript.Sleep nSeconds * 1000
End Sub
'= Method to pause for user to continue
Public Sub Pause
Prompt "Hit enter to continue..."
End Sub
END CLASS
Create a .vbs with the following code, which will open your main .vbs:
Set objShell = WScript.CreateObject("WScript.shell")
objShell.Run "cscript.exe ""C:\QuickTestb.vbs"""
Here is my main .vbs
Option Explicit
Dim i
for i = 1 To 5
Wscript.Echo i
Wscript.Sleep 5000
Next
You can run this script to echo in the command line
set wshShell = createObject("wscript.shell")
wshShell.run"cmd.exe /c echo something",1
For console output I use a snippet that quits elegantly if run in the wrong run-time. (And print is shorter to type...)
Sub print(s)
On Error Resume Next
WScript.stdout.WriteLine (s)
If err= &h80070006& Then WScript.Echo " Please run this script with CScript": WScript.quit
End Sub
print "hello"

Resources