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:
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 theOption Explicit
statement. If you don't get that error, you have anOn 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 theshutdown
command: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: