方法一:无限循环运行指定程序
Set WshShell = CreateObject("WScript.Shell")
' 设置程序路径(可以是.bat或.exe)
Dim programPath
programPath = "C:\path\to\your\program.bat" ' 修改为你的程序路径
' 无限循环
Do While True
' 运行程序
WshShell.Run Chr(34) & programPath & Chr(34), 1, True
' 等待时间(单位:毫秒),例如等待5秒
WScript.Sleep 5000
Loop
方法二:指定运行次数的循环
Set WshShell = CreateObject("WScript.Shell")
Dim programPath, maxRuns, runCount
programPath = "C:\path\to\your\program.exe" ' 修改为你的程序路径
maxRuns = 10 ' 设置运行次数
runCount = 0
For runCount = 1 To maxRuns
WScript.Echo "第 " & runCount & " 次运行"
' 运行程序(True表示等待程序结束)
WshShell.Run Chr(34) & programPath & Chr(34), 1, True
' 如果不是最后一次运行,则等待
If runCount < maxRuns Then
WScript.Sleep 3000 ' 等待3秒
End If
Next
WScript.Echo "程序已运行 " & maxRuns & " 次"
方法三:带错误处理的循环
Set WshShell = CreateObject("WScript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
Dim programPath
programPath = "C:\path\to\your\program.bat"
' 检查文件是否存在
If Not fso.FileExists(programPath) Then
WScript.Echo "错误:文件不存在 - " & programPath
WScript.Quit
End If
Do
On Error Resume Next ' 启用错误处理
' 运行程序
Dim returnCode
returnCode = WshShell.Run(Chr(34) & programPath & Chr(34), 1, True)
If Err.Number <> 0 Then
WScript.Echo "运行出错:" & Err.Description
Err.Clear
Else
WScript.Echo "程序运行完成,返回代码:" & returnCode
End If
' 询问是否继续
Dim answer
answer = MsgBox("是否继续运行程序?", vbYesNo + vbQuestion, "确认")
If answer = vbNo Then
Exit Do
End If
WScript.Sleep 2000
Loop While True
方法四:使用Windows任务计划程序(替代方案)
VBScript也可以创建计划任务实现循环:
' 创建每5分钟运行一次的计划任务
Set service = CreateObject("Schedule.Service")
Call service.Connect()
Dim rootFolder, taskDefinition
Set rootFolder = service.GetFolder("\")
Set taskDefinition = service.NewTask(0)
' 设置触发器(每分钟运行一次)
Dim trigger
Set trigger = taskDefinition.Triggers.Create(1) ' TASK_TRIGGER_TIME
trigger.StartBoundary = "2024-01-01T00:00:00"
trigger.Repetition.Interval = "PT5M" ' 每5分钟
trigger.Repetition.Duration = "P1D" ' 持续1天
trigger.Enabled = True
' 设置操作
Dim action
Set action = taskDefinition.Actions.Create(0) ' TASK_ACTION_EXEC
action.Path = "C:\path\to\your\program.bat"
action.Arguments = ""
' 注册任务
Call rootFolder.RegisterTaskDefinition("MyLoopTask", taskDefinition, 6, , , 3)
WScript.Echo "计划任务已创建"
方法五:后台静默运行(不显示窗口)
Set WshShell = CreateObject("WScript.Shell")
Dim programPath
programPath = "C:\path\to\your\program.exe"
Do While True
' 第二个参数0表示隐藏窗口运行
WshShell.Run Chr(34) & programPath & Chr(34), 0, True
' 等待10分钟
WScript.Sleep 600000
Loop
使用说明:
保存文件:将上述代码保存为
.vbs 文件(如
runloop.vbs)
修改路径:将
programPath 变量修改为你的实际程序路径
运行方式:
- 双击
.vbs 文件直接运行
- 使用命令
cscript runloop.vbs
注意事项:
权限问题:某些程序可能需要管理员权限
程序路径:如果路径包含空格,需要用引号包围
循环控制:考虑添加退出机制,避免无限循环
资源占用:长时间循环运行要注意系统资源使用
如果需要更复杂的控制逻辑,可以考虑使用PowerScript或专业的任务调度工具。