崩溃时重新启动vbs脚本 [英] Restart a vbs script if it crashes

查看:98
本文介绍了崩溃时重新启动vbs脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试制作一个vb脚本,如果该vb脚本崩溃,它将重新启动。
我搜索了,然后搜索了,但是我得到的只是如何重启程序,并且由于vb脚本是后台进程,因此在Win32_Process中搜索时不起作用。

I'm trying to make a vb script that will restart another vb script if it crashes. I have searched, and searched but all I get is how to restart a program and since a vb script is a background process it doesn't work when you search in 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

问题在于它永远不会看到文件正在运行,而只是打开数百个 Test_To_Stop.vbs文件,这解决了我不得不重新启动计算机的情况。

The problem is that it never see's the file running and just opens hundreds of "Test_To_Stop.vbs"'s which resolves in me having to restart the computer.

我认为应该改变

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

代替查看 Win32_Process,您需要查看后台进程在哪里运行。

Instead of looking in "Win32_Process" you need to look in wherever background process' run.

我是编码的新手,如果这是一个简单的问题,对不起。

I am new to coding so sorry if this is a simple question.

谢谢您。

问候

毒蛇

推荐答案

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

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"

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

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"

甚至更简单:

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"

这篇关于崩溃时重新启动vbs脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆