Restart a vbs script if it crashes

隐身守侯 提交于 2019-12-04 15:23:41

The below code restarts itself via WshShell.Exec() method and trace state of the running script via .Status property of returned object:

If Not WScript.Arguments.Named.Exists("task") Then
    Do
        With CreateObject("WScript.Shell").Exec("""" & WScript.FullName & """ """ & WScript.ScriptFullName & """ ""/task""")
            Do While .Status = 0
                WScript.Sleep 1
            Loop
        End With
    Loop
End If

MsgBox "This script will be restarted immediately after termination"

Another way is to use .Run() method with third parameter set to True to wait until launched process terminated:

If Not WScript.Arguments.Named.Exists("task") Then
    Do
        CreateObject("WScript.Shell").Run """" & WScript.FullName & """ """ & WScript.ScriptFullName & """ ""/task""", 1, True
    Loop
End If

MsgBox "This script will be restarted immediately after termination"

Or even simplier:

If Not WScript.Arguments.Named.Exists("task") Then
    Do
        CreateObject("WScript.Shell").Run """" & WScript.ScriptFullName & """ ""/task""", 1, True
    Loop
End If

MsgBox "This script will be restarted immediately after termination"

Probably because the name of the running process is 'wscript.exe' and not 'Test_To_Block.vbs'. You may be able to use the hack mentioned on this page to change the name of the process:

If you're running the scripts locally and running some regular scripts, one common hack is just to copy and rename wscript.exe to a particular name, such as "MyScript1.exe". Then run the script with a shortcut as "...\MyScript1.exe MyScript1.vbs". Then the process will show up as MyScript1.exe.

Then you can use sEXEName = "MyScript1.exe"

Note: instead of using Shell.run sExeName use Shell.run "Test_To_Block.vbs"

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!