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"
Related
I have the followaing run.vbs script
Rexe = "R-Portable\App\R-Portable\bin\Rscript.exe"
Ropts = "--no-save --no-environ --no-init-file --no-restore --no-Rconsole "
RScriptFile = "runShinyApp.R"
Outfile = "ShinyApp.log"
startChrome = "GoogleChromePortable\App\Chrome-bin\chrome.exe --app=http://127.0.0.1:9999"
strCommand = Rexe & " " & Ropts & " " & RScriptFile & " 1> " & Outfile & " 2>&1"
intWindowStyle = 0 ' Hide the window and activate another window.'
bWaitOnReturn = False ' continue running script after launching R '
' the following is a Sub call, so no parentheses around arguments'
CreateObject("Wscript.Shell").Run strCommand, intWindowStyle, bWaitOnReturn
WScript.Sleep 1000
CreateObject("Wscript.Shell").Run startChrome, intWindowStyle, bWaitOnReturn
It works pretty well in most cases except when the user puts the run.vbs script in a folder with spaces in its name: e.g. if run.vbs is in folder "foo bar", the user gets the error : "C:\Users\[user name]\Desktop\foo" not recognized as internal command...
I don't understand why Rscript.exe looks for the absolute path before running even if it's called from its parent directory using relative path.
I heard about the double quote solution using the absolute path but it doesn't seem to work with .exe scripts (it does though with .bat and .cmd)
Thanks for any help!
Below code will help you
Dim oShell As Object
Set oShell = CreateObject("WScript.Shell")
'run command'
Dim oExec As Object
Dim oOutput As Object
Set oExec = oShell.Exec("C:\Program Files\R\R-3.2.3\bin\Rscript.exe C:\subfolder\YourScript.R " & """" & var1 & """")
Set oOutput = oExec.StdOut
handle the results as they are written to and read from the StdOut object
Dim s As String
Dim sLine As String
While Not oOutput.AtEndOfStream
sLine = oOutput.ReadLine
If sLine <> "" Then s = s & sLine & vbCrLf
Wend
I'm getting Error code 800A0409, Unterminated string constant, on line 1, 54 with the code below.
Option Explicit
Dim ObjProgressMsg
Dim fso,objText,strVstup,strVystup,f,dtmVyt,dtmF,dDiff,fName,fExt,fShort,dtmAkt,tx,msgText
Dim strMessage,strWindowTitle,strTemp,wshShell,objTempMessage,strTempVBS
Set fso = CreateObject("Scripting.FileSystemObject")
Set objText = fso.GetFile("l:\bat\posledni.den")
strVstup = "l:\filefolder\"
strVystup = "l:\backup"
dtmVyt = objText.DateLastModified
msgText = "Some text about copying and renaming" & VbCrLf & "files, please wait..."
ProgressMsg msgText
For Each f In fso.GetFolder(strVstup).Files
dtmF = f.DateLastModified
dDiff = DateDiff("s", dtmF, dtmVyt)
If dDiff < 0 Then
ProgressMsg ""
WScript.Echo f
End If
Next
WScript.Echo "Some text about the task being finished."
Function ProgressMsg( strMessage )
' Written by Denis St-Pierre
' Displays a progress message box that the originating script can kill in both 2k and XP
' If StrMessage is blank, take down previous progress message box
' Using 4096 in Msgbox below makes the progress message float on top of things
' CAVEAT: You must have Dim ObjProgressMsg at the top of your script for this to work as described
Set wshShell = WScript.CreateObject( "WScript.Shell" )
strTEMP = wshShell.ExpandEnvironmentStrings( "%TEMP%" )
If strMessage = "" Then
' Disable Error Checking in case objProgressMsg doesn't exists yet
On Error Resume Next
' Kill ProgressMsg
objProgressMsg.Terminate( )
' Re-enable Error Checking
On Error Goto 0
Exit Function
End If
strTempVBS = strTEMP + "\" & "Message.vbs" 'Control File for reboot
' Create Message.vbs, True=overwrite
Set objTempMessage = fso.CreateTextFile( strTempVBS, True )
objTempMessage.WriteLine( "MsgBox""" & strMessage & """, 4096, """ & "a_sp_rano" & """" )
objTempMessage.Close
' Disable Error Checking in case objProgressMsg doesn't exists yet
On Error Resume Next
' Kills the Previous ProgressMsg
objProgressMsg.Terminate( )
' Re-enable Error Checking
On Error Goto 0
' Trigger objProgressMsg and keep an object on it
Set objProgressMsg = WshShell.Exec( "%windir%\system32\wscript.exe " & strTempVBS )
End Function
The script should show a msgbox while searching for files newer than last modified date of posledni.den file. Then once it finds a file it should close msgbox and echo the file it found.
It works just fine if I change this:
msgText = "Some text about copying and renaming" & VbCrLf & "files, please wait..."
to this:
msgText = "Some text about copying and renaming" & "files, please wait..."
Removal of VbCrLf seems to fix that error, just no line break is obviously happening. I can't figure out why it's behaving like that, what am I doing wrong. Every kind of insight on the problem would be much appreciated.
Thank you in advance. :)
The error occurs in the execution of the generated .vbs. What you do is:
>> msg1 = "A" & vbCrLf & "B"
>> code = "MsgBox """ & msg1 & """"
>> WScript.Echo code
>>
MsgBox "A
B"
>> Execute code
>>
Error Number: 1033
Error Description: Unterminated string constant
What you should do:
>> msg1 = """A"" & vbCrLf & ""B"""
>> WScript.Echo msg1
>>
"A" & vbCrLf & "B"
>> code = "MsgBox " & msg1 & ", 4096"
>> WScript.Echo code
>>
MsgBox "A" & vbCrLf & "B", 4096
>> Execute code
>>
>> <-- no news are good news; message displayed
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)
I need to write a diagnostic utility in VBS which i will package in my windows application installer.
I want the utility to run silently when the user is installing the application.
I tried:
Set pingCXS = objShell.Run("tracert -h 9 webaddress", 0, True)
Set pingCXSOutput = pingCXS.StdOut
strpingCXSOutput = pingCXSOutput.ReadAll
but it returns only the error code not the whole ping information.
When i use run method it gives a command window pop up:
Any other method to traceRT the webaddress without windows popup?
Also using a batch file is not a good option for me, as i have to use some WMI queries in the utility, which will require admin rights in batch file...
Please help out
Try this code :
Option Explicit
Dim ws,fso,TmpLogFile,Logfile,MyCmd,Webaddress,Param
Set ws = CreateObject("wscript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
TmpLogFile = "TmpFile.txt"
LogFile = Left(Wscript.ScriptFullName,InstrRev(Wscript.ScriptFullName, ".")) & "log"
If fso.FileExists(LogFile) Then fso.DeleteFile LogFile
webaddress = "www.stackoverflow.com"
Param = "-h 9"
MyCmd = "Tracert " & Param & " " & Webaddress & " >> "& TmpLogFile &_
" & cmd /U /C Type " & TmpLogFile & " > " & LogFile & " & Del " & TmpLogFile & ""
Call Run(MyCmd,0,True)
ws.run LogFile
'**********************************************************************************************
Function Run(StrCmd,Console,bWaitOnReturn)
Dim ws,MyCmd,Result
Set ws = CreateObject("wscript.Shell")
'A value of 0 to hide the MS-DOS console
If Console = 0 Then
MyCmd = "CMD /C " & StrCmd & ""
Result = ws.run(MyCmd,Console,bWaitOnReturn)
If Result = 0 Then
MsgBox "Success"
Else
MsgBox "An unknown error has occurred!",16,"An unknown error has occurred!"
End If
End If
'A value of 1 to show the MS-DOS console
If Console = 1 Then
MyCmd = "CMD /K " & StrCmd & ""
Result = ws.run(MyCmd,Console,bWaitOnReturn)
If Result = 0 Then
MsgBox "Success"
Else
MsgBox "An unknown error has occurred!",16,"An unknown error has occurred!"
End If
End If
Run = Result
End Function
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"