Yes/no shut down

2020-06-28 09:25发布

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

标签: vbscript
3条回答
唯我独甜
2楼-- · 2020-06-28 09:36

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.

查看更多
霸刀☆藐视天下
3楼-- · 2020-06-28 09:42

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.

查看更多
淡お忘
4楼-- · 2020-06-28 09:49

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
查看更多
登录 后发表回答