【问题标题】:VBS Check internet and delay script until ready [duplicate]VBS检查互联网并延迟脚本直到准备好[重复]
【发布时间】:2020-08-28 19:01:58
【问题描述】:

我有一个在用户登录时运行的 HTA 应用程序..

问题是有时 HTA 文件在互联网准备好之前打开很快,并且无法加载一些需要互联网连接的脚本..

所以我的计划是在调用脚本之前添加一个 ping 测试,然后暂停调用直到互联网连接准备好..

更新:

<html>
<head>
<title>Kiosk</title>
    <HTA:APPLICATION
    APPLICATIONNAME="Kiosk Launcher"
    ID="kiosklauncher"
    ICON="data/icon.ico"
    VERSION="1.0"
    CONTEXTMENU = "no"
    BORDER="none"
    INNERBORDER = "no"
    SINGLEINSTANCE = "yes"
    SHOWINTASKBAR = "yes"
    SCROLL="no"/>

<script Language="VBScript">
'--------------------------------------------------------------------------------------
Option Explicit
Dim Msg_Connected,Msg_NOT_Connected
Msg_Connected = "<h5><font color=""white""><strong>Starter Kiosk<strong></font></h5>"
        
Msg_NOT_Connected = "<h5><font color=""RED""><strong>Error no internet<strong></font></h5>"
'-------------------------------------------------------------------------------------- 
Sub Window_OnLoad()
Dim MyLoop,strComputer,objPing,objStatus,ws
Set ws = CreateObject("wscript.shell")
    window.resizeTo screen.availWidth/4,screen.availHeight/4
    window.moveTo screen.availWidth/2.7,screen.availHeight/2.5
'Call Shortcut()
MyLoop = True
While MyLoop
    strComputer = "smtp.gmail.com"
    Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}!\\").ExecQuery _
    ("select * from Win32_PingStatus where address = '" & strComputer & "'")
    For Each objStatus in objPing
        If objStatus.Statuscode = 0 Then
            MyLoop = False
            DataArea.InnerHTML = Msg_Connected
        Call Execute("SomeProgram.exe")
        Call Execute("BatScripts.bat")
        Call Sleep(1)
        Call RefreshExplorer
        Call Execute("AnotherProram.exe")
        Call Sleep(1)
        Call Execute("Launcher.bat")              
        call test()
            Exit for
        Else
            DataArea.InnerHTML = Msg_NOT_Connected
        End If
    Next
    Sleep(10) 'To sleep for 10 secondes
Wend
End Sub
    '-----------------------------Sleep-----------------------------------------
    Sub Sleep(seconds)
        CreateObject("WScript.Shell").Run "%COMSPEC% /c ping 127.0.0.1 -n " _
        & seconds+1, 0, True
    End Sub
    '-----------------------------TEST-----------------------------------------
    sub test()
    Window.Close
    end sub
    '----------------------------Execute---------------------------------------
    Sub Execute(Program)
        set shell=CreateObject("Shell.Application")
        ' shell.ShellExecute "application", "arguments", "path", "verb", window
        shell.ShellExecute ""&Program&"",,"data\", "runas", 0
        set shell=nothing
    End sub
        '-----------------------------RefreshExplorer-----------------------------------
    Function RefreshExplorer() 
        dim strComputer, objWMIService, colProcess, objProcess  
        strComputer = "." 
        'Get WMI object  
        Set objWMIService = GetObject("winmgmts:" _ 
        & "{impersonationLevel=impersonate}!\\" _  
        & strComputer & "\root\cimv2")  
        Set colProcess = objWMIService.ExecQuery _ 
        ("Select * from Win32_Process Where Name = 'explorer.exe'") 
        For Each objProcess in colProcess 
        objProcess.Terminate() 
        Next  
    End Function

</script>

</head>

<body>

        <div class="main">
        <center><h2 style="text-align: center;">Kiosk Launcher</h2></center>
        <center><div><img src="data/preloader.gif" class="preloader-scale" draggable="false" unselectable="on"></div></center>
        <center><h4>Please wait</h4></center>
        <center><span id="DataArea"></span></center>
        </div>

</body>
</html>

【问题讨论】:

  • 也许我可以让它工作..当我将脚本复制并粘贴到我的 HTA 文件中时,我收到错误:变量未定义“wscript”不知道我该如何解决..
  • “复制和粘贴”不加修改绝不是构建脚本的方法,首先要了解它在做什么,然后从那里整合。重要的部分是使用带有延迟的循环来检查连接,您已经在检查连接,您只需要在循环中运行它并在成功连接时中断循环。
  • 就像我说的:“没有任何 vbs 编码技能,这超出了我的简单编辑技能。”
  • 在这种情况下,您要么需要聘请某人为您编写代码,要么您需要学习一些东西。无论哪种方式Stack Overflow 都不是代码编写服务,我们在这里帮助为明确定义的问题提供答案,当 OP 不理解他们所询问的主题时,这会更加困难。该副本清楚地说明了如何循环检查连接。如果您无法实施,我们可以提供帮助。

标签: vbscript ping delayed-execution


【解决方案1】:

在此处参考此答案Error: Object required: 'wscript' in HTA

HTA 引擎不提供 WScript 对象,因此 WScript.QuitWScript.SleepWscript.Echo 之类的内容在 HTA 中不起作用。

要以编程方式退出 HTA,请使用 Self.Closewindow.Close

要替换Sleep 方法,请参阅this question 的答案。


我做了一个小例子让你检查连接,我替换了

wscript.echowscript.echo (不能像我上面说的那样工作)&lt;span id="DataArea"&gt;&lt;/span&gt;

这是整个 HTA:


<html>
<head>
<title>Network Diagnostics And Checking Internet Connection by Hackoo 2020</title>
<HTA:APPLICATION
 Application ID = "Check_Internet_Connection"
 APPLICATIONNAME = "Check_Internet_Connection"
 BORDER="THIN"
 BORDERSTYLE="NORMAL"
 CAPTION = "Yes"
 CONTEXTMENU = "Yes"
 ICON = "nslookup.exe"
 INNERBORDER="NO"
 MAXIMIZEBUTTON="NO"
 MINIMIZEBUTTON="YES"
 SCROLL="NO"
 SELECTION="NO
 SHOWINTASKBAR = "Yes"
 SINGLEINSTANCE = "Yes"
 SYSMENU = "Yes"
/>
<style type="text/css">
  body {
        font-family:Verdana;
        font-size: 10x;
        color: #49403B;
        background: LightGreen;
        }
 </style>
</head>
<script Language="VBScript">
'--------------------------------------------------------------------------------------
Option Explicit
Dim Msg_Connected,Msg_NOT_Connected
Msg_Connected = "<Marquee DIRECTION=""Right"" SCROLLAMOUNT=""6"" BEHAVIOR=""ALTERNATE"">"&_
        "<h2><font color=""GREEN""><strong>You Are Now Connected To The Internet !<strong></font></h2></Marquee><br><br>"&_
        "<img src=""https://cdn2.unrealengine.com/Fortnite%2FBoogieDown_GIF-1f2be97208316867da7d3cf5217c2486da3c2fe6.gif""></img>"
        
Msg_NOT_Connected = "<Marquee DIRECTION=""Right"" SCROLLAMOUNT=""6"" BEHAVIOR=""ALTERNATE"">"&_
        "<h3><font color=""RED""><strong>You Are Not Connected to the Internet ... We are trying to establish again your connection<strong></font></h3></Marquee>"
'--------------------------------------------------------------------------------------
Sub CenterWindow( widthX, heightY )
    self.ResizeTo widthX, heightY 
    self.MoveTo (screen.Width - widthX)/2, (screen.Height - heightY)/2
End Sub
'-------------------------------------------------------------------------------------- 
Sub Window_OnLoad()
Dim MyLoop,strComputer,objPing,objStatus,ws
Set ws = CreateObject("wscript.shell")
CenterWindow 800,600
Call Shortcut()
MyLoop = True
While MyLoop
    strComputer = "smtp.gmail.com"
    Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}!\\").ExecQuery _
    ("select * from Win32_PingStatus where address = '" & strComputer & "'")
    For Each objStatus in objPing
        If objStatus.Statuscode = 0 Then
            MyLoop = False
            DataArea.InnerHTML = Msg_Connected
            WAN_IP.InnerHTML = "<h2><font color=""GREEN""><strong> WAN IP : " & Get_WAN_IP & "<strong></font></h2>"
            SayIt()
            'Call MyProgram() ' You can call all your Programs here after the connection has been established !
            Exit for
        Else
            DataArea.InnerHTML = Msg_NOT_Connected
            ws.run "%SystemRoot%\system32\msdt.exe -skip TRUE -path %Windir%\diagnostics\system\networking -ep NetworkDiagnosticsPNI"
        End If
    Next
    Sleep(10) 'To sleep for 10 secondes
Wend
End Sub
'--------------------------------------------------------------------------------------
 Sub Sleep(seconds)
    CreateObject("WScript.Shell").Run "CMD /c ping 127.0.0.1 -n " & seconds,0,True
End Sub
'--------------------------------------------------------------------------------------
Function Get_WAN_IP()
Dim http
Set http = CreateObject("Microsoft.XMLHTTP" )
http.Open "GET", "http://icanhazip.com", False
http.Send
Get_WAN_IP= http.responseText  
End Function
'--------------------------------------------------------------------------------------
Sub SayIt()
Dim fso,WaveFile,ws
Set ws = CreateObject("wscript.Shell")
Set fso = CreateObject("Scripting.FileSystemObject")
WaveFile = WS.ExpandEnvironmentStrings("%LocalAppData%\Microsoft\Windows Sidebar\Gadgets\NetworkMonitorII.gadget\media\established.wav")
If fso.FileExists(WaveFile) Then
    Play(WaveFile)
    Sleep(5)
    Play("http://94.23.221.158:9197/stream")
Else
    CreateObject("SAPI.SpVoice").Speak "You are Connected to the internet"
    Sleep(5)
    Play("http://94.23.221.158:9197/stream")
End If
End Sub
'--------------------------------------------------------------------------------------
Sub Play(URL)
    Dim ws,fso,f,TempName,TempFile,TempFolder
    Set ws = CreateObject("wscript.Shell")
    Set fso = CreateObject("Scripting.FileSystemObject")
    Tempname = fso.GetTempName
    TempFolder = WS.ExpandEnvironmentStrings("%Temp%")
    TempFile = TempFolder & "\" & Tempname & ".vbs"
    Set f = fso.OpenTextFile(Tempfile,2,True)
    f.Writeline     "Call Play(" & chr(34) & URL & chr(34) & ")"
    f.Writeline "Sub Play(URL)"
    f.Writeline "Set Sound = CreateObject(""WMPlayer.OCX"")"
    f.Writeline "Sound.URL = URL"
    f.Writeline "Sound.settings.volume = 100"                               
    f.Writeline "Sound.Controls.play"                                     
    f.Writeline "do while Sound.currentmedia.duration = 0"                
    f.Writeline     "wscript.sleep 100"                                       
    f.Writeline "loop"                                                    
    f.Writeline "wscript.sleep (int(Sound.currentmedia.duration)+1)*1000" 
    f.Writeline "End Sub"
    f.close
    ws.run Tempfile
End Sub
'--------------------------------------------------------------------------------------
Sub Stop_Playing()
    Dim Command,ws
    Set ws = CreateObject("wscript.Shell")
    Command = "Cmd /C Taskkill /IM ""wscript.exe"" /F >nul 2>&1"
    ws.run Command,0,True
    Exit Sub
End Sub
'--------------------------------------------------------------------------------------
Sub Window_OnUnload()
    Call Stop_Playing()
End Sub
'--------------------------------------------------------------------------------------
sub Shortcut()
dim shell,DesktopPath,Link,CurrentFolder,FullName,arrFN,HTA_Name
Set Shell = CreateObject("WScript.Shell")
CurrentFolder = shell.CurrentDirectory
DesktopPath = Shell.SpecialFolders("Desktop")
FullName = replace(Check_Internet_Connection.commandLine,chr(34),"")  
arrFN=split(FullName,"\")  
HTA_Name = arrFN(ubound(arrFN))
Link = GetFilenameWithoutExtension(HTA_Name)
Set link = Shell.CreateShortcut(DesktopPath & "\" & Link & ".lnk")
link.Description = HTA_Name
link.IconLocation = "nslookup.exe"
link.TargetPath = CurrentFolder & "\" & HTA_Name
link.WorkingDirectory = CurrentFolder
Link.HotKey = "CTRL+ALT+C"
link.Save
end Sub
'--------------------------------------------------------------------------------------
Function GetFilenameWithoutExtension(FileName)
    Dim Result, i
    Result = FileName
    i = InStrRev(FileName, ".")
    If ( i > 0 ) Then
        Result = Mid(FileName, 1, i - 1)
    End If
    GetFilenameWithoutExtension = Result
End Function
'-------------------------------------------------------------------------------------
</script>
<body>
    <center>
        <span id="DataArea"></span>
        </br></br>
        <span id="WAN_IP"></span>
    </center>
</body>
</html>

编辑:28/08/2020 @ 12:02

<html>
<head>
<title>Kiosk</title>
    <HTA:APPLICATION
    APPLICATIONNAME="Kiosk Launcher"
    ID="kiosklauncher"
    ICON="data/icon.ico"
    VERSION="1.0"
    CONTEXTMENU = "no"
    BORDER="none"
    INNERBORDER = "no"
    SINGLEINSTANCE = "yes"
    SHOWINTASKBAR = "yes"
    SCROLL="no"/>

<script Language="VBScript">
'--------------------------------------------------------------------------------------
Option Explicit
Dim Msg_Connected,Msg_NOT_Connected
Msg_Connected = "<h5><font color=""white""><strong>Starter Kiosk<strong></font></h5>"
        
Msg_NOT_Connected = "<h5><font color=""RED""><strong>Error no internet<strong></font></h5>"
'-------------------------------------------------------------------------------------- 
Sub Window_OnLoad()
    Dim MyLoop,strComputer,objPing,objStatus,ws
    Set ws = CreateObject("wscript.shell")
    window.resizeTo screen.availWidth/4,screen.availHeight/4
    window.moveTo screen.availWidth/2.7,screen.availHeight/2.5
    MyLoop = True
    While MyLoop
        strComputer = "smtp.gmail.com"
        Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}!\\").ExecQuery _
        ("select * from Win32_PingStatus where address = '" & strComputer & "'")
        For Each objStatus in objPing
            If objStatus.Statuscode = 0 Then
                MyLoop = False
                DataArea.InnerHTML = Msg_Connected
'Call Execute("SomeProgram.exe")
'Call Execute("BatScripts.bat")
                Call Sleep(1)
'Call RefreshExplorer
'Call Execute("AnotherProram.exe")
                Call Sleep(1)
'Call Execute("Launcher.bat")              
'call test()
                MsgBox  "You are now connected to the Internet ! " & vbCrLf &_
                "And The splash screen will exit now after you clicked on this Message Box !"
                Call CloseHTA()
'Exit for
            Else
                DataArea.InnerHTML = Msg_NOT_Connected
            End If
        Next
        Sleep(10) 'To sleep for 10 secondes
    Wend
End Sub
'-----------------------------Sleep-----------------------------------------
Sub Sleep(seconds)
    CreateObject("WScript.Shell").Run "%COMSPEC% /c ping 127.0.0.1 -n " & seconds+1,0, True
End Sub
'-----------------------------TEST-----------------------------------------
Sub CloseHTA()
    Self.Close
End sub
'----------------------------Execute---------------------------------------
Sub Execute(Program)
    Dim Shell ' You forget here to declare the variable Shell so be careful
    set shell=CreateObject("Shell.Application")
' shell.ShellExecute "application", "arguments", "path", "verb", window
    shell.ShellExecute ""&Program&"",,"data\", "runas", 0
    set shell=nothing
End sub
'-----------------------------RefreshExplorer-----------------------------------
Function RefreshExplorer() 
    dim strComputer, objWMIService, colProcess, objProcess  
    strComputer = "." 
'Get WMI object  
    Set objWMIService = GetObject("winmgmts:" _ 
    & "{impersonationLevel=impersonate}!\\" _  
    & strComputer & "\root\cimv2")  
    Set colProcess = objWMIService.ExecQuery _ 
    ("Select * from Win32_Process Where Name = 'explorer.exe'") 
    For Each objProcess in colProcess 
        objProcess.Terminate() 
    Next  
End Function
</script>
</head>
<body>
        <div class="main">
        <center><h2 style="text-align: center;">Kiosk Launcher</h2></center>
        <center><div><img src="data/preloader.gif" class="preloader-scale" draggable="false" unselectable="on"></div></center>
        <center><h4>Please wait</h4></center>
        <center><span id="DataArea"></span></center>
        </div>
</body>
</html>

【讨论】:

  • 太棒了!我希望你能看到 Hackoo 这个话题。我一直在玩这个脚本。我想我可以用它做一些事情。我注意到的唯一问题是我用来居中和调整 HTA 的脚本基于分辨率中断的窗口,当我添加脚本时它抱怨未定义变量“widthX”。我已经在主题中添加了我的来源..
  • @Xenosis 现在重新检查一下,我为您更新了 HTA!
  • 好的,我现在有时间来处理脚本了。我不得不说这给我带来了很多麻烦。当我将 ping 脚本添加到我的工作 Splash.hta 时,其他一切似乎都因未定义的变量而中断。我的窗口根据分辨率调整大小,我的执行程序脚本中断。为什么它会与我的工作代码混淆?我已经用我的 Splash.hta 文件更新了主题..
  • @Xenosis 您忘记声明Dim Shell 并检查编辑的代码!如果您可以批量压缩所有文件和 HTA 并将其作为链接发布在您的下一条评论中,我想尝试您的整个项目!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-11-30
  • 2012-03-23
  • 1970-01-01
  • 2011-07-18
  • 2013-08-16
  • 2017-01-25
  • 2011-09-02
相关资源
最近更新 更多