Related
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"
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
'----------------------------------------------------------------------------------
There is a great answer providing a batch file what will allways do it's best to run elevated and will not elevate if already elevated.
I don't want to distribute the batch file with my program though. The whole core of the answer is this VBSScript:
Set UAC = CreateObject("Shell.Application")
UAC.ShellExecute "[path to the batch file which will run elevated]", "ELEV", "", "runas", 1
Pretty simple. So just instead of the path to the batch file, I want to use the path to a jar file. But it doesn't seem to work:
Set UAC = CreateObject("Shell.Application")
UAC.ShellExecute "AutoClient.jar", "ELEV", "", "runas", 1
Set UAC = CreateObject("Shell.Application")
UAC.ShellExecute "javaw -jar AutoClient.jar", "ELEV", "", "runas", 1
Set UAC = CreateObject("Shell.Application")
UAC.ShellExecute "javaw", "ELEV", "-jar AutoClient.jar", "runas", 1
So well, how can I run the jar from the vbs file? Both files share the same directory. It's necessary that java application's working directory is that directory.
Edit:
So thanks #MCND (and this) I now know that the arguments go as follows:
path to executable to run
command line parameters sent to the program
working directory of the new process
'runas' command which invokes elevation
0 means do not show the window, 1 to show the window
And thanks to his code:
Set UAC = CreateObject("Shell.Application")
UAC.ShellExecute "javaw.exe", "-jar AutoClient.jar", "", "runas", 1
I can add another error in my collection:
The documentation states that the first parameter in the call is the file to start, leaving the arguments to the second parameter. So it should be (sorry, not tested)
Set UAC = CreateObject("Shell.Application")
UAC.ShellExecute "javaw.exe", "-jar AutoClient.jar", "", "runas", 1
So far, the only way I made this work without crazy popup errors is:
' Get the script location, the directorry where it's running
Set objShell = CreateObject("Wscript.Shell")
strPath = Wscript.ScriptFullName
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.GetFile(strPath)
strFolder = objFSO.GetParentFolderName(objFile)
' Args:
' path to executable to run
' command line parameters - first parameter of this file, which is the jar file name
' working directory (this doesn't work but I use it nevertheless)
' runas command which invokes elevation
' 0 means do not show the window. Normally, you show the window, but not this console window
' which just blinks and disappears anyway
UAC.ShellExecute "run-normally.bat", "SomeFile.jar, strFolder, "runas", 0
Because the working directory parameter doesn't work, I have following two lines in the bat file:
rem Used as a helper for the elevating VBS script. Runs the jar file
rem given as 1st argument as if the file was double clicked.
rem Make sure we're on our CURRENT directory
cd /d %~dp0
rem Run java, expecting the jar file to be given as the 1st argument
javaw -jar %1
I am not satisfied with this solution for cosmetic reasons. I want to display the UAC message for JRE, not windows command line:
I don't use Java but you aren't specifing full paths. You can't expect things to work reliably. Also whatever you are starting will need to have on it's right click menu Run As Administrator because the VBS code runs that menu command as if you clicked it. If it's not there you can't click it. EXE have it. So specify the correct paths to both Javaw and the jar file.
One issue is that the current directory is different depending on what technique you are using. ALWAYS specify full paths.
Here's a script that lists what verbs are available for an object (not we are not working with files but with objects). The graphical shell (explorer) is an object browser and has no idea what a file is apart from the fact it's an object of some type.
---------------------------
Windows Script Host
---------------------------
ShVerb
Lists or runs an explorer verb (right click menu) on a file or folder
ShVerb <filename> [verb]
Used without a verb it lists the verbs available for the file or folder
The program lists most verbs but only ones above the first separator
of the menu work when used this way
The Properties verb can be used. However the program has to keep running
to hold the properties dialog open. It keeps running by displaying
a message box.
---------------------------
OK
---------------------------
The script
HelpMsg = vbcrlf & " ShVerb" & vbcrlf & vbcrlf & " David Candy 2014" & vbcrlf & vbcrlf & " Lists or runs an explorer verb (right click menu) on a file or folder" & vbcrlf & vbcrlf & " ShVerb <filename> [verb]" & vbcrlf & vbcrlf & " Used without a verb it lists the verbs available for the file or folder" & vbcrlf & vbcrlf
HelpMsg = HelpMsg & " The program lists most verbs but only ones above the first separator" & vbcrlf & " of the menu work when used this way" & vbcrlf & vbcrlf
HelpMsg = HelpMsg & " The Properties verb can be used. However the program has to keep running" & vbcrlf & " to hold the properties dialog open. It keeps running by displaying" & vbcrlf & " a message box."
Set objShell = CreateObject("Shell.Application")
Set Ag = WScript.Arguments
set WshShell = WScript.CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
If Ag.count = 0 then
wscript.echo " ShVerb - No file specified"
wscript.echo HelpMsg
wscript.quit
Else If Ag.count = 1 then
If LCase(Replace(Ag(0),"-", "/")) = "/h" or Replace(Ag(0),"-", "/") = "/?" then
wscript.echo HelpMsg
wscript.quit
End If
ElseIf Ag.count > 2 then
wscript.echo vbcrlf & " ShVerb - To many parameters" & vbcrlf & " Use quotes around filenames and verbs containing spaces" & vbcrlf
wscript.echo HelpMsg
wscript.quit
End If
If fso.DriveExists(Ag(0)) = True then
Set objFolder = objShell.Namespace(fso.GetFileName(Ag(0)))
' Set objFolderItem = objFolder.ParseName(fso.GetFileName(Ag(0)))
Set objFolderItem = objFolder.self
msgbox ag(0)
ElseIf fso.FolderExists(Ag(0)) = True then
Set objFolder = objShell.Namespace(fso.GetParentFolderName(Ag(0)))
Set objFolderItem = objFolder.ParseName(fso.GetFileName(Ag(0)))
ElseIf fso.fileExists(Ag(0)) = True then
Set objFolder = objShell.Namespace(fso.GetParentFolderName(Ag(0)))
Set objFolderItem = objFolder.ParseName(fso.GetFileName(Ag(0)))
Else
wscript.echo " ShVerb - " & Ag(0) & " not found"
wscript.echo HelpMsg
wscript.quit
End If
Set objVerbs = objFolderItem.Verbs
'If only one argument list verbs for that item
If Ag.count = 1 then
For Each cmd in objFolderItem.Verbs
If len(cmd) <> 0 then CmdList = CmdList & vbcrlf & replace(cmd.name, "&", "")
Next
wscript.echo mid(CmdList, 2)
'If two arguments do verbs for that item
ElseIf Ag.count = 2 then
For Each cmd in objFolderItem.Verbs
If lcase(replace(cmd, "&", "")) = LCase(Ag(1)) then
wscript.echo(Cmd.doit)
Exit For
End If
Next
'Properties is special cased. Script has to stay running for Properties dialog to show.
If Lcase(Ag(1)) = "properties" then
WSHShell.AppActivate(ObjFolderItem.Name & " Properties")
msgbox "This message box has to stay open to keep the " & ObjFolderItem.Name & " Properties dialog open."
End If
End If
End If
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"
Is there a way to display a message box from a batch file (similar to how xmessage can be used from bash-scripts in Linux)?
First of all, DOS has nothing to do with it, you probably want a Windows command line solution (again: no DOS, pure Windows, just not a Window, but a Console).
You can either use the VBScript method provided by boflynn or you can mis-use net send or msg. net send works only on older versions of windows:
net send localhost Some message to display
This also depends on the Messenger service to run, though.
For newer versions (XP and onward, apparently):
msg "%username%" Some message to display
It should be noted that a message box sent using msg.exe will only last for 60 seconds. This can however be overridden with the /time:xx switch.
I would make a very simple VBScript file and call it using CScript to parse the command line parameters.
Something like the following saved in MessageBox.vbs:
Set objArgs = WScript.Arguments
messageText = objArgs(0)
MsgBox messageText
Which you would call like:
cscript MessageBox.vbs "This will be shown in a popup."
MsgBox reference if you are interested in going this route.
Might display a little flash, but no temp files required. Should work all the way back to somewhere in the (IIRC) IE5 era.
mshta javascript:alert("Message\n\nMultiple\nLines\ntoo!");close();
Don't forget to escape your parentheses if you're using if:
if 1 == 1 (
mshta javascript:alert^("1 is equal to 1, amazing."^);close^(^);
)
This will pop-up another Command Prompt window:
START CMD /C "ECHO My Popup Message && PAUSE"
Try :
Msg * "insert your message here"
If you are using Windows XP's command.com, this will open a message box.
Opening a new cmd window isn't quite what you were asking for, I gather.
You could also use VBScript, and use this with your .bat file. You would open it from the bat file with this command:
cd C:\"location of vbscript"
What this does is change the directory command.com will search for files from, then on the next line:
"insert name of your vbscript here".vbs
Then you create a new Notepad document, type in
<script type="text/vbscript">
MsgBox "your text here"
</script>
You would then save this as a .vbs file (by putting ".vbs" at the end of the filename), save as "All Files" in the drop down box below the file name (so it doesn't save as .txt), then click Save!
Few more ways.
1) The geekiest and hackiest - it uses the IEXPRESS to create small exe that will create a pop-up with a single button (it can create two more types of pop-up messages). Works on EVERY windows from XP and above:
;#echo off
;setlocal
;set ppopup_executable=popupe.exe
;set "message2=click OK to continue"
;
;del /q /f %tmp%\yes >nul 2>&1
;
;copy /y "%~f0" "%temp%\popup.sed" >nul 2>&1
;(echo(FinishMessage=%message2%)>>"%temp%\popup.sed";
;(echo(TargetName=%cd%\%ppopup_executable%)>>"%temp%\popup.sed";
;(echo(FriendlyName=%message1_title%)>>"%temp%\popup.sed"
;
;iexpress /n /q /m %temp%\popup.sed
;%ppopup_executable%
;rem del /q /f %ppopup_executable% >nul 2>&1
;pause
;endlocal
;exit /b 0
[Version]
Class=IEXPRESS
SEDVersion=3
[Options]
PackagePurpose=InstallApp
ShowInstallProgramWindow=1
HideExtractAnimation=1
UseLongFileName=0
InsideCompressed=0
CAB_FixedSize=0
CAB_ResvCodeSigning=0
RebootMode=N
InstallPrompt=%InstallPrompt%
DisplayLicense=%DisplayLicense%
FinishMessage=%FinishMessage%
TargetName=%TargetName%
FriendlyName=%FriendlyName%
AppLaunched=%AppLaunched%
PostInstallCmd=%PostInstallCmd%
AdminQuietInstCmd=%AdminQuietInstCmd%
UserQuietInstCmd=%UserQuietInstCmd%
SourceFiles=SourceFiles
[SourceFiles]
SourceFiles0=C:\Windows\System32\
[SourceFiles0]
%FILE0%=
[Strings]
AppLaunched=subst.exe
PostInstallCmd=<None>
AdminQuietInstCmd=
UserQuietInstCmd=
FILE0="subst.exe"
DisplayLicense=
InstallPrompt=
2) Using MSHTA. Also works on every windows machine from XP and above (despite the OP do not want "external" languages the JavaScript here is minimized). Should be saved as .bat:
#if (true == false) #end /*!
#echo off
mshta "about:<script src='file://%~f0'></script><script>close()</script>" %*
goto :EOF */
alert("Hello, world!");
or in one line:
mshta "about:<script>alert('Hello, world!');close()</script>"
or
mshta "javascript:alert('message');close()"
or
mshta.exe vbscript:Execute("msgbox ""message"",0,""title"":close")
3) Here's parameterized .bat/jscript hybrid (should be saved as bat). It again uses JavaScript despite the OP request but as it is a bat it can be called as a bat file without worries. It uses POPUP which allows a little bit more control than the more popular MSGBOX. It uses WSH, but not MSHTA like in the example above.
#if (#x)==(#y) #end /***** jscript comment ******
#echo off
cscript //E:JScript //nologo "%~f0" "%~nx0" %*
exit /b 0
#if (#x)==(#y) #end ****** end comment *********/
var wshShell = WScript.CreateObject("WScript.Shell");
var args=WScript.Arguments;
var title=args.Item(0);
var timeout=-1;
var pressed_message="button pressed";
var timeout_message="timed out";
var message="";
function printHelp() {
WScript.Echo(title + "[-title Title] [-timeout m] [-tom \"Time-out message\"] [-pbm \"Pressed button message\"] [-message \"pop-up message\"]");
}
if (WScript.Arguments.Length==1){
runPopup();
WScript.Quit(0);
}
if (args.Item(1).toLowerCase() == "-help" || args.Item(1).toLowerCase() == "-h" ) {
printHelp();
WScript.Quit(0);
}
if (WScript.Arguments.Length % 2 == 0 ) {
WScript.Echo("Illegal arguments ");
printHelp();
WScript.Quit(1);
}
for (var arg = 1 ; arg<args.Length;arg=arg+2) {
if (args.Item(arg).toLowerCase() == "-title") {
title = args.Item(arg+1);
}
if (args.Item(arg).toLowerCase() == "-timeout") {
timeout = parseInt(args.Item(arg+1));
if (isNaN(timeout)) {
timeout=-1;
}
}
if (args.Item(arg).toLowerCase() == "-tom") {
timeout_message = args.Item(arg+1);
}
if (args.Item(arg).toLowerCase() == "-pbm") {
pressed_message = args.Item(arg+1);
}
if (args.Item(arg).toLowerCase() == "-message") {
message = args.Item(arg+1);
}
}
function runPopup(){
var btn = wshShell.Popup(message, timeout, title, 0x0 + 0x10);
switch(btn) {
// button pressed.
case 1:
WScript.Echo(pressed_message);
break;
// Timed out.
case -1:
WScript.Echo(timeout_message);
break;
}
}
runPopup();
4) and one jscript.net/.bat hybrid (should be saved as .bat) .This time it uses .NET and compiles a small .exe file that could be deleted:
#if (#X)==(#Y) #end /****** silent jscript comment ******
#echo off
::::::::::::::::::::::::::::::::::::
::: compile the script ::::
::::::::::::::::::::::::::::::::::::
setlocal
::if exist "%~n0.exe" goto :skip_compilation
:: searching the latest installed .net framework
for /f "tokens=* delims=" %%v in ('dir /b /s /a:d /o:-n "%SystemRoot%\Microsoft.NET\Framework\v*"') do (
if exist "%%v\jsc.exe" (
rem :: the javascript.net compiler
set "jsc=%%~dpsnfxv\jsc.exe"
goto :break_loop
)
)
echo jsc.exe not found && exit /b 0
:break_loop
call %jsc% /nologo /out:"%~n0.exe" "%~f0"
::::::::::::::::::::::::::::::::::::
::: end of compilation ::::
::::::::::::::::::::::::::::::::::::
:skip_compilation
::
::::::::::
"%~n0.exe" %*
::::::::
::
endlocal
exit /b 0
****** end of jscript comment ******/
import System;
import System.Windows;
import System.Windows.Forms
var arguments:String[] = Environment.GetCommandLineArgs();
MessageBox.Show(arguments[1],arguments[0]);
5) and at the end one single call to powershell that creates a pop-up (can be called from command line or from batch if powershell is installed):
powershell [Reflection.Assembly]::LoadWithPartialName("""System.Windows.Forms""");[Windows.Forms.MessageBox]::show("""Hello World""", """My PopUp Message Box""")
6) And the dbenham's approach seen here
start "" cmd /c "echo(&echo(&echo Hello world! &echo(&pause>nul"
7) For a system tray notifications you can try this:
call SystemTrayNotification.bat -tooltip warning -time 3000 -title "Woow" -text "Boom" -icon question
This way your batch file will create a VBS script and show a popup. After it runs, the batch file will delete that intermediate file.
The advantage of using MSGBOX is that it is really customaziable (change the title, the icon etc) while MSG.exe isn't as much.
echo MSGBOX "YOUR MESSAGE" > %temp%\TEMPmessage.vbs
call %temp%\TEMPmessage.vbs
del %temp%\TEMPmessage.vbs /f /q
Here's a PowerShell variant that doesn't require loading assemblies prior to creating the window, however it runs noticeably slower (~+50%) than the PowerShell MessageBox command posted here by #npocmaka:
powershell (New-Object -ComObject Wscript.Shell).Popup("""Operation Completed""",0,"""Done""",0x0)
You can change the last parameter from "0x0" to a value below to display icons in the dialog (see Popup Method for further reference):
0x10 Stop
0x20 Question Mark
0x30 Exclamation Mark
0x40 Information Mark
Adapted from the Microsoft TechNet article PowerTip: Use PowerShell to Display Pop-Up Window.
echo X=MsgBox("Message Description",0+16,"Title") >msg.vbs
–you can write any numbers from 0,1,2,3,4 instead of 0 (before the ‘+’ symbol) & here is the meaning of each number:
0 = Ok Button
1 = Ok/Cancel Button
2 = Abort/Retry/Ignore button
3 = Yes/No/Cancel
4 = Yes/No
–you can write any numbers from 16,32,48,64 instead of 16 (after the ‘+’ symbol) & here is the meaning of each number:
16 – Critical Icon
32 – Warning Icon
48 – Warning Message Icon
64 – Information Icon
Msg * "insert your message here"
works fine, just save as a .bat file in notepad or make sure the format is set to "all files"
msg * /time:0 /w Hello everybody!
This message waits forever until OK is clicked (it lasts only one minute by default) and works fine in Windows 8.1
In order to do this, you need to have a small program that displays a messagebox and run that from your batch file.
You could open a console window that displays a prompt though, but getting a GUI message box using cmd.exe and friends only is not possible, AFAIK.
Following on #Fowl's answer, you can improve it with a timeout to only appear for 10 seconds using the following:
mshta "javascript:var sh=new ActiveXObject( 'WScript.Shell' ); sh.Popup( 'Message!', 10, 'Title!', 64 );close()"
See here for more details.
You can invoke dll function from user32.dll i think
Something like
Rundll32.exe user32.dll, MessageBox (0, "text", "titleText", {extra flags for like topmost messagebox e.t.c})
Typing it from my Phone, don't judge me... otherwise i would link the extra flags.
I use a utility named msgbox.exe from here:
http://www.paulsadowski.com/WSH/cmdprogs.htm
You can use Zenity, which posts regular releases on download.gnome.org. Zenity allows for the execution of dialog boxes in command-line and shell scripts. More info can also be found on Wikipedia.
It is cross-platform, but I couldn't find a recent win32 build. Unfortunately placella.com went offline. A Windows installer of v3.20 (from March 2016) can be found here.
This application can do that, if you convert (wrap) your batch files into executable files.
Simple Messagebox
%extd% /messagebox Title Text
Error Messagebox
%extd% /messagebox Error "Error message" 16
Cancel Try Again Messagebox
%extd% /messagebox Title "Try again or Cancel" 5
4) "Never ask me again" Messagebox
%extd% /messageboxcheck Title Message 0 {73E8105A-7AD2-4335-B694-94F837A38E79}
Here is my batch script that I put together based on the good answers here & in other posts
You can set title timeout & even sleep to schedule it for latter & \n for new line
Name it popup.bat & put it in your windows path folder to work globally on your pc
For example popup Line 1\nLine 2 will produce a 2 line popup box
(type popup /? for usage)
Here is the code
<!-- : Begin CMD
#echo off
cscript //nologo "%~f0?.wsf" %*
set pop.key=[%errorlevel%]
if %pop.key% == [-1] set pop.key=TimedOut
if %pop.key% == [1] set pop.key=Ok
if %pop.key% == [2] set pop.key=Cancel
if %pop.key% == [3] set pop.key=Abort
if %pop.key% == [4] set pop.key=Retry
if %pop.key% == [5] set pop.key=Ignore
if %pop.key% == [6] set pop.key=Yes
if %pop.key% == [7] set pop.key=No
if %pop.key% == [10] set pop.key=TryAgain
if %pop.key% == [11] set pop.key=Continue
if %pop.key% == [99] set pop.key=NoWait
exit /b
-- End CMD -->
<job><script language="VBScript">
'on error resume next
q =""""
qsq =""" """
Set objArgs = WScript.Arguments
Set objShell= WScript.CreateObject("WScript.Shell")
Popup = 0
Title = "Popup"
Timeout = 0
Mode = 0
Message = ""
Sleep = 0
button = 0
If objArgs.Count = 0 Then
Usage()
ElseIf objArgs(0) = "/?" or Lcase(objArgs(0)) = "-h" or Lcase(objArgs(0)) = "--help" Then
Usage()
End If
noWait = Not wait()
For Each arg in objArgs
If (Mid(arg,1,1) = "/") and (InStr(arg,":") <> 0) Then haveSwitch = True
Next
If not haveSwitch Then
Message=joinParam("woq")
Else
For i = 0 To objArgs.Count-1
If IsSwitch(objArgs(i)) Then
S=split(objArgs(i) , ":" , 2)
select case Lcase(S(0))
case "/m","/message"
Message=S(1)
case "/tt","/title"
Title=S(1)
case "/s","/sleep"
If IsNumeric(S(1)) Then Sleep=S(1)*1000
case "/t","/time"
If IsNumeric(S(1)) Then Timeout=S(1)
case "/b","/button"
select case S(1)
case "oc", "1"
button=1
case "ari","2"
button=2
case "ync","3"
button=3
case "yn", "4"
button=4
case "rc", "5"
button=5
case "ctc","6"
button=6
case Else
button=0
end select
case "/i","/icon"
select case S(1)
case "s","x","stop","16"
Mode=16
case "?","q","question","32"
Mode=32
case "!","w","warning","exclamation","48"
Mode=48
case "i","information","info","64"
Mode=64
case Else
Mode=0
end select
end select
End If
Next
End If
Message = Replace(Message,"/\n", "°" )
Message = Replace(Message,"\n",vbCrLf)
Message = Replace(Message, "°" , "\n")
If noWait Then button=0
Wscript.Sleep(sleep)
Popup = objShell.Popup(Message, Timeout, Title, button + Mode + vbSystemModal)
Wscript.Quit Popup
Function IsSwitch(Val)
IsSwitch = False
If Mid(Val,1,1) = "/" Then
For ii = 3 To 9
If Mid(Val,ii,1) = ":" Then IsSwitch = True
Next
End If
End Function
Function joinParam(quotes)
ReDim ArgArr(objArgs.Count-1)
For i = 0 To objArgs.Count-1
If quotes = "wq" Then
ArgArr(i) = q & objArgs(i) & q
Else
ArgArr(i) = objArgs(i)
End If
Next
joinParam = Join(ArgArr)
End Function
Function wait()
wait=True
If objArgs.Named.Exists("NewProcess") Then
wait=False
Exit Function
ElseIf objArgs.Named.Exists("NW") or objArgs.Named.Exists("NoWait") Then
objShell.Exec q & WScript.FullName & qsq & WScript.ScriptFullName & q & " /NewProcess: " & joinParam("wq")
WScript.Quit 99
End If
End Function
Function Usage()
Wscript.Echo _
vbCrLf&"Usage:" _
&vbCrLf&" popup followed by your message. Example: ""popup First line\nescaped /\n\nSecond line"" " _
&vbCrLf&" To triger a new line use ""\n"" within the msg string [to escape enter ""/"" before ""\n""]" _
&vbCrLf&"" _
&vbCrLf&"Advanced user" _
&vbCrLf&" If any Switch is used then you must use the /m: switch for the message " _
&vbCrLf&" No space allowed between the switch & the value " _
&vbCrLf&" The switches are NOT case sensitive " _
&vbCrLf&"" _
&vbCrLf&" popup [/m:""*""] [/t:*] [/tt:*] [/s:*] [/nw] [/i:*]" _
&vbCrLf&"" _
&vbCrLf&" Switch | value |Description" _
&vbCrLf&" -----------------------------------------------------------------------" _
&vbCrLf&" /m: /message:| ""1 2"" |if the message have spaces you need to quote it " _
&vbCrLf&" | |" _
&vbCrLf&" /t: /time: | nn |Duration of the popup for n seconds " _
&vbCrLf&" | |<Default> untill key pressed" _
&vbCrLf&" | |" _
&vbCrLf&" /tt: /title: | ""A B"" |if the title have spaces you need to quote it " _
&vbCrLf&" | | <Default> Popup" _
&vbCrLf&" | |" _
&vbCrLf&" /s: /sleep: | nn |schedule the popup after n seconds " _
&vbCrLf&" | |" _
&vbCrLf&" /nw /NoWait | |Continue script without the user pressing ok - " _
&vbCrLf&" | | botton option will be defaulted to OK button " _
&vbCrLf&" | |" _
&vbCrLf&" /i: /icon: | ?/q |[question mark]" _
&vbCrLf&" | !/w |[exclamation (warning) mark]" _
&vbCrLf&" | i/info|[information mark]" _
&vbCrLf&" | x/stop|[stop\error mark]" _
&vbCrLf&" | n/none|<Default>" _
&vbCrLf&" | |" _
&vbCrLf&" /b: /button: | o |[OK button] <Default>" _
&vbCrLf&" | oc |[OK and Cancel buttons]" _
&vbCrLf&" | ari |[Abort, Retry, and Ignore buttons]" _
&vbCrLf&" | ync |[Yes, No, and Cancel buttons]" _
&vbCrLf&" | yn |[Yes and No buttons]" _
&vbCrLf&" | rc |[Retry and Cancel buttons]" _
&vbCrLf&" | ctc |[Cancel and Try Again and Continue buttons]" _
&vbCrLf&" ---> | ---> |The output will be saved in variable ""pop.key""" _
&vbCrLf&"" _
&vbCrLf&"Example:" _
&vbCrLf&" popup /tt:""My MessageBox"" /t:5 /m:""Line 1\nLine 2\n/\n\nLine 4""" _
&vbCrLf&"" _
&vbCrLf&" v1.9 By RDR # 2020"
Wscript.Quit
End Function
</script></job>
Bat file:
#echo off
echo wscript.Quit((msgbox("question?",4+32+256, "title")-6) Mod 255) > %temp%\msgbox.vbs
start /wait %temp%\msgbox.vbs
rem echo wscript returned %errorlevel%
if errorlevel 1 goto error
echo We have Yes
goto end
:error
echo We have No
:end
del %temp%\msgbox.vbs /f /q
I would create a batch subroutine MSGBOX like shown below which you can call then via
call :MSGBOX "Test-Message 1" "Test-Title 1"
as often you want.
For example:
#ECHO OFF
:: call message box sub-routine
call :MSGBOX "Test-Message 1" "Test-Title 1"
call :MSGBOX "Test-Message 2" "Test-Title 2"
:END
EXIT /B
::::::::::::::::
:: sub-routines
:MSGBOX
:: 1. parameter: message
:: 2. parameter: title
:: find temporary name for VBS file
:uniqueLoop
set "uniqueFileName=%tmp%\msgbox~%RANDOM%.vbs"
if exist "%uniqueFileName%" goto :uniqueLoop
:: write to temporary VBS file, execute, delete file
echo msgbox"%~1",vbInformation , "%~2"> %uniqueFileName%
%uniqueFileName%
erase %uniqueFileName%
EXIT /B
msg * /server:127.0.0.1 Type your message here
A better option
set my_message=Hello world&& start cmd /c "#echo off & mode con cols=15 lines=2 & echo %my_message% & pause>nul"
Description:
lines= amount of lines,plus 1
cols= amount of characters in the message, plus 3 (However, minimum must be 15)
Auto-calculated cols version:
set my_message=Hello world&& (echo %my_message%>EMPTY_FILE123 && FOR %? IN (EMPTY_FILE123 ) DO SET strlength=%~z? && del EMPTY_FILE123 ) && start cmd /c "#echo off && mode con lines=2 cols=%strlength% && echo %my_message% && pause>nul"
it needs ONLY to popup when inside a vm, so technically, there should be some code like:
if %machine_type% == virtual_machine then
echo message box code
else
continue normal installation code