VBS Freezes When Waiting on Cmd Prompt - vbscript

Hard to make a concise title, but basically, I have started an instance of command prompt from VBS to run an exe, everything works great and I verify my feedback with msgboxes of output line. When the command prompt gets to a part that is loading and says Verifying File (XX%), the VBS does not run anymore. It does not crash, it simply never moves on from its line. I even have noticed that if I don't constantly Writeline, it will pause before that. So while I wait, I constantly write a 1. I dont see anywhere it could be in an infinite loop without showing me a messagebox.
Please help.
set shell = WScript.CreateObject("WScript.Shell")
set oExec = Shell.exec("cmd.exe")
do while Not oExec.StdOut.AtEndOfStream
junkChar = oExec.stdOut.Read(1)
message = message & junkChar
'errormsg = oExec.stderr.readline
if asc(junkChar) = 13 and message <> junkChar then
msgbox message '& len(message)
message = ""
end if
if right(message,1) = ">" and not bool1stCmd then
'msgbox(message)
msgbox("Command" & cmdArchive)
oExec.stdIn.Writeline cmdArchive
bool1stCmd = True
'oExec.StdIn.Write VbCrLf
elseif bool1stCmd then
if InStr(1,message,"Enter a command>")>0 then
msgbox "Enter a command!"
end if
oExec.stdIn.writeline "1"
end if
msgbox "Loop again!"
Loop
msgbox "exiting loop"

Related

vbscript X and Cancel not doing what they should

im writing a code in vbscript where it will ask the user for input and then run certain files according to the input and i have the else so that it will redo the if else sequence when you type something that isnt an option but when i try to press cancel or the red 'X' it acts as if i have put in an invalid input and goes over the else sequence.
Dim sInput
sInput = InputBox("input")
If sInput = "input1" or sInput = "input2" Then
set shell=createobject("wscript.shell")
shell.run "file.bat"
elseif sInput = "exit" or sInput = "Exit" Then
WScript.Quit
else
name=msgbox (" That is not a valid response",0+16,"ERROR")
set shell=createobject("wscript.shell")
shell.run "input.vbs"
end if
Don't try to restart the script.
Use a loop instead. End the loop when the user entered a valid option, or quit the entire program if requested.
Option Explicit
Dim Shell, input, button
Set Shell = CreateObject("WScript.Shell")
Do
input = InputBox("input")
If IsEmpty(input) Or LCase(input) = "exit" Then WScript.Quit
input = LCase(Trim(input))
If input = "input1" Or input = "input2" Then
Shell.Run "file.bat"
Exit Do
Else
button = MsgBox("That is not a valid response.", vbExclamation + vbRetryCancel, "ERROR")
If button = vbCancel Then Exit Do
End If
Loop
Notes:
Option Explicit makes variable declaration mandatory. It's a good idea to always have this enabled.
IsEmpty() is true when the user pressed the Cancel button (or the Esc key) in the InputBox - but this will work only before the response is manipulated in any way, such as LCase or Trim. Supporting the Cancel button is more intuitive than having a special "exit" keyword, so maybe you should get rid of that.
The various constants you can use with MsgBox are described on ss64.com and in more detal in the official VBScript language reference.
You can change what Enter and Esc do in each MsgBox by using the vbDefaultButton1 or vbDefaultButton2 constants.
The Do loop without any conditions (Do/Loop While ... or Do/Loop Until ...) will run forever - be sure not to forget using Exit Do or WScript.Quit(). (If you do, killing the Script with the Task Manager will get you out of it.)

In VBScript, I can not stop my loop from repeating

I have looked hard to resolve this issue, but I am coming up short.
Here is my code:
'attempts and completions loop
'attempts
do
do
Wscript.StdOut.WriteLine "How many attempts did " & QB & " throw: "
attempts = Wscript.StdIn.ReadLine
if IsNumeric(attempts) then
attempts = CInt(attempts)
else
Wscript.StdOut.Write "You did not enter a number. Please try again."
end if
loop while IsNumeric(attempts) = false
'completions
do
Wscript.StdOut.WriteLine "How many completed passes did " & QB & " throw for: "
completions = Wscript.StdIn.ReadLine
if IsNumeric(completions) then
attempts = CInt(completions)
else
Wscript.StdOut.Write "You did not enter a number. Please try again."
end if
loop while (completions) = false
if attempts > completions then
exit do
else
Wscript.StdOut.Writeline "Completions can not be more that attempts please try again."
end if
loop while attempts < completions
When I enter more completions than attempts, I get my desire result. But when I enter more attempts than completes it will still loop through this code. Can I please get some assistance.
Nevermind my comment...I see it now. In the loop for Completions, you are setting the attempts variable when you should be setting the completions variable.
if IsNumeric(completions) then
attempts = CInt(completions)
So when you're comparing, attempts is always blank or whatever you've initialized it to.
Standard copy/paste error :)

How to click on ok button in message box using vbscript

I have written a simple script to press ok on message box but its not working. Please help me how to do this
here is the sample code
set oWShell = createobject("WScript.Shell")
MsgBox "Hello"
WScript.Sleep 2000
oWShell.Sendkeys "{enter}"
MsgBox waits for the click. If you don't click yourself, it gets never to "Sleep" or "SendKeys".
I assume you are just trying to learn, because this code makes no sense. If you want to press a button on another programs window, this could work. But in its own process this doesn't work.
If you really want to click your own MsgBox, you have to do it with a separate script. One creates the MsgBox and another clicks the button.
If you just want to close a message box after a certain period of time, check out the Popup() method of the WshShell class. Its second parameter specifies the number of seconds to display the message box for before closing it.
With CreateObject("WScript.Shell")
' Display a message box that disappears after two seconds...
.Popup "Hello", 2
End With
chek this site
you need this:
Set objArgs = WScript.Arguments
messageText = objArgs(0)
MsgBox messageText, 51, "Warning......!"
how to click on button in message box and control of display time here the script can do that .
just copy this lines of code and paste in text file then save it as "ControlMsgBox.vbs".
''' IN THE NAME OF ALLAH
' THIS SCRIPT CONTROL OF MSGBOX DISPLAY TIME
' LET SENKEYS DEAL WITH THE MSGBOX
' SOLVE THE PROBLEM OF APPACTIVATE NOT WORKING EFFECTIVE
On Error Resume Next
Dim Sh : Set Sh=CreateObject("wscript.shell") ' declare and create the wshshell
Dim path : path =Replace(WScript.ScriptFullName,WScript.ScriptName,"") 'declare the variable of the current script path
Dim myMessage : myMessage="This is my message ." 'declare variable of the of the display text of msgbox
Sh.run "cmd.exe /c cd """&path&""" && echo msgbox """&myMessage&""",,""hello"" > mymsgbox.vbs",0,false 'create masgbox script in the same path
WScript.Sleep 1000 'wait 1 sec to let process of create msgbox script execute
Sh.run "mymsgbox.vbs" 'run the created msgbox script
WScript.Sleep 3000 ' let the msgbox display for 3 sec before we sendkeys to close
For i=0 To 600 ' loop to retry select correct msgbox window about 1 min
ret = Sh.AppActivate("In_The_Name_Of_Allah") 'select the activate msgbox window (if this loop 300 this mean loop will continue 30 sec if 600 (1 min)
If ret = True Then ' check if the msgbox windows select or not
Sh.SendKeys "%N" 'send key of Alt+N to select first button in msgbox (ok)
End If
ret = Sh.AppActivate("In_The_Name_Of_Allah") 'recheck again to be sure that we will not send key out of target windows (msgbox window)
If ret = True Then
Sh.SendKeys "{enter}" ' send key to click enter
wscript.sleep 500
ret=Sh.AppActivate("In_The_Name_Of_Allah")
If ret=False Then ' using nested IF to sure of selected windows is false because its close
Exit For ' exit for loop directly and execute what after for next
End If
End If
WScript.Sleep 100
Next
With CreateObject("Scripting.FileSystemObject")
If .FileExists(path&"mymsgbox.vbs") Then 'check if the msgbox script we create form this script exist or not
.DeleteFile(path&"mymsgbox.vbs") 'delete the msgbox script we create after message window closed
End If
End With
Set Sh=Nothing 'remove the sh object create
WScript.Quit ' terminate wscript.exe instance who run this script

Run script in background

I want to run following script as scheduled task on Windows 7 in background. Now, script displays cmd window and, can I run script without visible cmd window?
Option Explicit
Dim WshShell, oExec
Dim RegexParse
Dim hasError : hasError = 0
Set WshShell = WScript.CreateObject("WScript.Shell")
Set RegexParse = New RegExp
Set oExec = WshShell.Exec("%comspec% /c echo list volume | diskpart.exe")
RegexParse.Pattern = "\s\s(Volume\s\d)\s+([A-Z])\s+(.*)\s\s(NTFS|FAT)\s+(Mirror|RAID-5)\s+(\d+)\s+(..)\s\s([A-Za-z]*\s?[A-Za-z]*)(\s\s)*.*"
While Not oExec.StdOut.AtEndOfStream
Dim regexMatches
Dim Volume, Drive, Description, Redundancy, RaidStatus
Dim CurrentLine : CurrentLine = oExec.StdOut.ReadLine
Set regexMatches = RegexParse.Execute(CurrentLine)
If (regexMatches.Count > 0) Then
Dim match
Set match = regexMatches(0)
If match.SubMatches.Count >= 8 Then
Volume = match.SubMatches(0)
Drive = match.SubMatches(1)
Description = Trim(match.SubMatches(2))
Redundancy = match.SubMatches(4)
RaidStatus = Trim(match.SubMatches(7))
End If
If RaidStatus <> "Healthy" Then
hasError = 1
'WScript.StdOut.Write "WARNING "
MsgBox "Status of " & Redundancy & " " & Drive & ": (" & Description & ") is """ & RaidStatus & """", 16, "RAID error"
End If
End If
Wend
WScript.Quit(hasError)
Thanks a lot
Option 1 - If the task is running under your user credentials (if not, msgbox will not be visible)
There are two possible sources for the cmd window.
a) The script itself. If the task is executing cscript, the console window will be visible, avoid it calling wscript instead
b) The Shell.exec call. The only way to hide this window is to start the calling script hidden. On start of your script test for the presence of certain argument. If not present, make the script call itself with the argument, using Run method of the WshShell object, and indicating to run the script with hidden window. Second instance of the script will start with the special parameter, so it will run, but this time windows will be hidden.
Option 2 - Running the task under system credentials.
In this case, no window will be visible. All will be running in a separate session. BUT msgbox will not be seen. Change MsgBox call with a call to msg.exe and send a message to current console user.

Yes/no shut down

I am playing with VBScript and I want to make a MsgBox which asks the user if they want to shut down their computer or not.
If the user clicks Yes they should see a MsgBox first then their computer starts to shutdown.
I am using this code but it doesn't work.
What is the problem?
result = MsgBox ("Shutdown?", vbYesNo, "Yes/No Exm")
Select Case result
Case vbYes
MsgBox("shuting down ...")
Option Explicit
Dim objShell
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "C:\WINDOWS\system32\shutdown.exe -r -t 0"
Case vbNo
MsgBox("Ok")
End Select
I have amended your code as per below:
Option Explicit
Dim result
result = MsgBox ("Shutdown?", vbYesNo, "Yes/No Exm")
Select Case result
Case vbYes
MsgBox("shuting down ...")
Dim objShell
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run "C:\WINDOWS\system32\shutdown.exe -r -t 20"
Case vbNo
MsgBox("Ok")
End Select
The main issues were that "option explicit" has to be at the top, and as a result the "result" variable then must be declared using the "dim" keyword. The above code works fine when I executed it via the command line.
I also added a timeout of 20, but you can easily change this back to the original value of 0.
As documented Option Explicit must appear before any other statement in a script. Using it anywhere else in a script should raise a "Expected Statement" error pointing to the line with the Option Explicit statement. If you don't get that error, you have an On Error Resume Next in your code that you didn't show.
If you move the Option Explicit statement to the beginning of the script, but the shutdown still doesn't occur, you need to check the return value of the shutdown command:
rc = objShell.Run "C:\WINDOWS\system32\shutdown.exe -r -t 0", 0, True
If rc <> 0 Then MsgBox "shutdown failed with exit code " & rc & "."
The parentheses in your MsgBox statements shouldn't cause an issue as long as you pass just a single argument to the function, but I'd still remove them.
Try This:
Set Shell = CreateObject("WScript.Shell")
Answer = MsgBox("Do You Want To" & vbNewLine & "Shut Down Your Computer?",vbYesNo,"Shutdown:")
If Answer = vbYes Then
Shell.run "shutdown.exe -s -t 60"
Ending = 1
ElseIf Answer = vbNo Then
Stopping = MsgBox("Do You Wish To Quit?",vbYesNo,"Quit:")
If Stopping = vbYes Then
WScript.Quit 0
End If
End If

Resources