如果崩溃,请重新启动 vbs 脚本

Restart a vbs script if it crashes

我正在尝试制作一个 vb 脚本,如果它崩溃,它将重新启动另一个 vb 脚本。 我搜索了又搜索,但我得到的只是如何重新启动程序,因为 vb 脚本是后台进程,所以当您在 Win32_Process.

中搜索时它不起作用

这是我的代码

set Service = GetObject ("winmgmts:")
set Shell = WScript.CreateObject("WScript.Shell")

sEXEName = "Test_To_Block.vbs"

while true
 bRunning = false

 for each Process in Service.InstancesOf ("Win32_Process")
  if Process.Name = sEXEName then
   bRunning=true
   msgbox("I am active")
  End If
 next


if bRunning=False then
 msgbox("I am not active.")
 Shell.Run sEXEName
end if


WScript.Sleep(100)

wend

问题是它永远看不到文件 运行ning,只会打开数百个 "Test_To_Stop.vbs",这让我不得不重新启动计算机。

我认为应该更改的是代码查找的位置。

for each Process in Service.InstancesOf ("Win32_Process")

您无需查看 "Win32_Process",而是需要查看后台进程的任何位置 运行。

我是编码新手,很抱歉这是一个简单的问题。

提前致谢。

此致,

毒蛇

可能是因为 运行ning 进程的名称是 'wscript.exe' 而不是 'Test_To_Block.vbs'。您可以使用 this 页面上提到的 hack 来更改进程的名称:

如果您运行在本地安装脚本并运行安装一些常规脚本,一个 常见的 hack 只是将 wscript.exe 复制并重命名为特定名称, 比如"MyScript1.exe"。然后 运行 脚本的快捷方式为 “...\MyScript1.exe MyScript1.vbs”。然后该过程将显示为 MyScript1.exe.

那你可以用sEXEName = "MyScript1.exe"

注意:不要使用 Shell.run sExeName,而是使用 Shell.run "Test_To_Block.vbs"

以下代码通过 WshShell.Exec() 方法自行重启,并通过返回对象的 .Status 属性 跟踪 运行 脚本的状态:

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"

另一种方法是使用 .Run() 方法并将第三个参数设置为 True 以等待启动的进程终止:

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"

或者更简单:

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"