为什么我不能重新打开我的浏览器(对象)?

Why I can't re-open my browser(object)?

我想创建一个脚本来打开有一些限制的 Internet Explorer 浏览器。脚本验证 iexplorer.exe 进程是否 运行ning 如果不是(意味着浏览器已关闭)它会在 10 秒后自动重新打开它。

这是脚本:

strComputer = "."

Set objWMIService = GetObject("winmgmts:\" & strComputer & "\root\cimv2")
Set objShell = CreateObject("Wscript.Shell")
Set objExplorer = CreateObject("InternetExplorer.Application")
Const REOPEN_AFTER =10000


objExplorer.Navigate "http://www.google.com"
objExplorer.Visible = true
objExplorer.ToolBar = false
objExplorer.MenuBar = false
objExplorer.StatusBar = false
objExplorer.AddressBar = true
objExplorer.Width = 1280
objExplorer.Height = 1024
objExplorer.Left = 0
objExplorer.Top = 0
objExplorer.Resizable = false

Do While True
    Set colProcesses = objWMIService.ExecQuery _
        ("Select * from Win32_Process Where Name = 'iexplore.exe'")
    If colProcesses.Count = False Then
        objExplorer.Navigate "http://www.google.com" 
        objExplorer.Visible = true

    End If
    Wscript.Sleep REOPEN_AFTER
Loop

如果我启动脚本,它 运行 会打开浏览器,但如果我关闭它,它不会重新打开。

但是如果我 运行 它是这样的,那么它就可以工作:

strComputer = "."

Set objWMIService = GetObject("winmgmts:\" & strComputer & "\root\cimv2")
Set objShell = CreateObject("Wscript.Shell")
Set objExplorer = CreateObject("InternetExplorer.Application")
Const REOPEN_AFTER =10000


objExplorer.Navigate "http://www.google.com"
objExplorer.Visible = true
objExplorer.ToolBar = false
objExplorer.MenuBar = false
objExplorer.StatusBar = false
objExplorer.AddressBar = true
objExplorer.Width = 1280
objExplorer.Height = 1024
objExplorer.Left = 0
objExplorer.Top = 0
objExplorer.Resizable = false

Do While True
    Set colProcesses = objWMIService.ExecQuery _
        ("Select * from Win32_Process Where Name = 'iexplore.exe'")
    If colProcesses.Count = 0 Then
        objShell.Run "iexplorer.exe"
    End If
    Wscript.Sleep REOPEN_AFTER
Loop

谁能看出错误在哪里?

将对象实例化移到 if colProcesses.Count=0 Then

当导航器关闭时,变量中存储的对象引用无效。您需要一个新实例。

我认为当您关闭浏览器时,objExplorer 无效,而当您尝试

If colProcesses.Count = False Then
    objExplorer.Navigate "http://www.google.com" 
    objExplorer.Visible = true
End If

它将失败,因为它不再指向打开的浏览器 - 我认为此时您只需要创建一个新的 IE 实例,例如:

function createExplorer

    Set createExplorer = CreateObject("InternetExplorer.Application")
    createExplorer.Navigate "http://www.google.com"
    createExplorer.Visible = true
    createExplorer.ToolBar = false
    createExplorer.MenuBar = false
    createExplorer.StatusBar = false
    createExplorer.AddressBar = true
    createExplorer.Width = 1280
    createExplorer.Height = 1024
    createExplorer.Left = 0
    createExplorer.Top = 0
    createExplorer.Resizable = false

end function



Do While True
    Set colProcesses = objWMIService.ExecQuery _
    ("Select * from Win32_Process Where Name = 'iexplore.exe'")
    If colProcesses.Count = 0 Then
        Set objExplorer = createExplorer()
    End If
    Wscript.Sleep REOPEN_AFTER
Loop