Frage

I am trying to make a pretty simple .vbs in Notepad that will do the following, but I am having a bit of trouble as I am a little new to scripting:

  • Execute a .bat if you select 'Yes', and close the window and do nothing if you select 'No'.

  • Display a message so you know why you're hitting 'Yes' or 'No'.

  • Display a window title.

Here's what I have tried to make myself so far:

x=msgbox("MESSAGE HERE",4,"WINDOW TITLE HERE")
const Hidden = 0
const WaitOnReturn = true
set WshShell = CreateObject("WScript.Shell")
WshShell.Run "%HOMEPATH%\Documents\FOLDER\FOLDER\EXAMPLE.BAT", Hidden, WaitOnReturn
WScript.Echo "Done"

It works just fine, however, even if I select 'No', it will still execute the .bat, which I do not want.

War es hilfreich?

Lösung

Try this code :

Option Explicit
Const Hidden = 0
Const WaitOnReturn = True
Dim Question,BatchFilePath,Message,Title,Result
Title = "Running a .bat through a .vbs"
Message = "Did you want to continue executing this script"
BatchFilePath = "%ProgramFiles%\FolderTest\Folder Name with spaces\EXAMPLE.BAT"
'We add the double quotes in this variable to bypass spaces issues in the path
BatchFilePath = DblQuote(BatchFilePath)
Question = Msgbox(Message,VbYesNo + VbQuestion,Title)
If Question = VbNo Then
    MsgBox "You have chosen to quit this script !",vbExclamation,Title
    WScript.Quit() ' We quit the script
Else
    Result = Run(BatchFilePath,Hidden,WaitOnReturn)
End If
'*********************************************************************
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",VbInformation,Title
        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",VbInformation,Title
        Else
            MsgBox "An unknown error has occurred!",16,"An unknown error has occurred!"
        End If
    End If
    Run = Result
End Function
'*********************************************************************
Function DblQuote(Str)
    DblQuote = Chr(34) & Str & Chr(34)
End Function
'*********************************************************************

Andere Tipps

Try this one:

Set obj = CreateObject("WScript.shell")

Answer = MsgBox("Content Here",vbYesNo,"Title Here")
If Answer = vbYes Then
obj.Run "PATH TO BATCH FILE"
Else
WScript.Quit 0
End If
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top