Below code is to check whether a network connection on the machine is established.
Dim T = 0
While(T = 0)
Set Http = WScript.CreateObject("MSXML2.ServerXMLHTTP")
Http.Open "GET", "http://www.google.com/", True
Http.Send
If(Http.Status = 200) Then
MsgBox "Network Connection is established"
T = 1
else
MsgBox "Network Connection isn't established yet"
End If
Wend
Whether or not network is connected, the Http.Status returns value 200.
Could anyone assist whether I'm missing anything here.
Refer to this ==> Loop a function?
You can do it easily with this code :
Option Explicit
Dim MyLoop,strComputer,objPing,objStatus
MyLoop = True
While MyLoop = True
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
Call MyProgram()
wscript.quit
End If
Next
Pause(10) 'To sleep for 10 secondes
Wend
'**********************************************************************************************
Sub Pause(NSeconds)
Wscript.Sleep(NSeconds*1000)
End Sub
'**********************************************************************************************
Sub MyProgram()
Dim WshShell
set WshShell = WScript.CreateObject("WScript.Shell")
On Error Resume Next
With WScript.CreateObject ("InternetExplorer.Application")
.Navigate "http://www.example.com/slideshow"
.fullscreen = 1
.Visible = 1
WScript.Sleep 10000
End With
On Error Goto 0
End Sub
'**********************************************************************************************
EDIT :
Wscript.echo(CheckConnection("https://www.google.com"))
'----------------------------------------------------
Function CheckConnection(URL)
On Error Resume Next 'swallow errors
Set o = CreateObject("MSXML2.XMLHTTP")
o.open "GET",URL, False
o.send
If Err.Number <> 0 Then
CheckConnection = "An error occured. Data not retrieved."
'or whatever else you want to do in such a case.
Else
CheckConnection = "You are connected"
End If
On Error Goto 0 'back to normal error behaviour
End Function
'----------------------------------------------------
Related
How Can I pause speak command in vbscript? I have to play it from the same paused position.
Code block:
Dim Speak, Path
Path = "string"
Path = "C:\Users\sony\Desktop\TheReunion.txt"
const ForReading = 1
Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile(Path,ForReading)
strFileText = objFileToRead.ReadAll()
Set Speak=CreateObject("sapi.spvoice")
Speak.Speak strFileText
objFileToRead.Close
Set objFileToRead = Nothing
You need to call the speak method asynchronously before using the pause and resume methods as mentioned by LotPings in the comments.
Code:
Dim Speak, Path
Path = "string"
Path = "C:\Users\sony\Desktop\TheReunion.txt"
const ForReading = 1
Set objFileToRead = CreateObject("Scripting.FileSystemObject").OpenTextFile(Path,ForReading)
strFileText = objFileToRead.ReadAll()
Set Speak=CreateObject("sapi.spvoice")
Speak.Speak strFileText,1 '1=Asynchronous. Click the link below for other possible values "SpeechVoiceSpeakFlags"
'Due to async call to speak method, we can proceed with the code execution while the voice is being played in the background. Now we can call pause and resume methods
wscript.sleep 5000 'voice played for 5000ms
Speak.pause 'paused
wscript.sleep 4000 'remains paused for 4000ms
Speak.resume 'resumes
objFileToRead.Close
Set objFileToRead = Nothing
SpeechVoiceSpeakFlags
Intrigue in this led me to take inspiration from Kira's answer and develop it somewhat (in a bad, novice kind of way), to achieve the pause/resume objective interactively, the code below works for me, and hopefully it's of some help to you...
option explicit
dim strpath, fso, strfile, strtxt, user, voice, flag
flag = 2
call init
sub init
do while len(strpath) = 0
strpath = inputbox ("Please enter the full path of txt file", "Txt to Speech")
if isempty(strpath) then
wscript.quit()
end if
loop
'strpath = "C:\Users\???\Desktop\???.txt"
set fso = createobject("scripting.filesystemobject")
on error resume next
set strfile = fso.opentextfile(strpath,1)
if err.number = 0 then
strtxt = strfile.readall()
strfile.close
call ctrl
else
wscript.echo "Error: " & err.number & vbcrlf & "Source: " & err.source & vbcrlf &_
"Description: " & err.description
err.clear
call init
end if
end sub
sub ctrl
user = msgbox("Press ""OK"" to Play / Pause", vbokcancel + vbexclamation, "Txt to Speech")
select case user
case vbok
if flag = 0 then
voice.pause
flag = 1
call ctrl
elseif flag = 1 then
voice.resume
flag = 0
call ctrl
else
call spk
end if
case vbcancel
wscript.quit
end select
end sub
sub spk
'wscript.echo strtxt
set voice = createobject("sapi.spvoice")
voice.speak strtxt,1
flag = 0
call ctrl
end sub
I have here a VBScript to "toggle" my network adapter (built from a script found on the Internet).
I was wondering if maybe someone can help me convert it to a script that can "reset" (disable, then re-enable) my wireless adapter, rather than toggle it.
'~ Toggle a SPECIFIED NIC on or off
Option Explicit
Const NETWORK_CONNECTIONS = &H31&
Dim objShell, objFolder, objFolderItem, objEnable, objDisable
Dim folder_Object, target_NIC
Dim NIC, clsVerb
Dim str_NIC_Name, strEnable, strDisable
Dim bEnabled, bDisabled
'NIC name goes here VVV
str_NIC_Name = "Wi-Fi"
strEnable = "En&able"
strDisable = "Disa&ble"
' create objects and get items
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(NETWORK_CONNECTIONS)
Set objFolderItem = objFolder.Self
Set folder_Object = objFolderItem.GetFolder
Set target_NIC = Nothing
' look at each NIC and match to the chosen name
For Each NIC In folder_Object.Items
If LCase(NIC.Name) = LCase(str_NIC_Name) Then
' proper NIC is found, get it
Set target_NIC = NIC
End If
Next
bEnabled = True
Set objEnable = Nothing
Set objDisable = Nothing
For Each clsVerb In target_NIC.Verbs
'~ Wscript.Echo clsVerb
If clsVerb.Name = strEnable Then
Set objEnable = clsVerb
bEnabled = False
End If
If clsVerb.Name = strDisable Then
Set objDisable = clsVerb
End If
Next
If bEnabled Then
objDisable.DoIt
Else
objEnable.DoIt
End If
'~ Give the connection time to change
WScript.Sleep 5000
I think it's better to use WMI (Windows Management Instrumentation).
Here is a sample script:
Option Explicit
dim ComputerName
dim WMIService, NIC
dim ConnectionName
ComputerName = "."
ConnectionName = "Ethernet"
if not IsElevated then
WScript.Echo "Please run this script with administrative rights!"
WScript.Quit
end if
On Error Resume Next
Set WMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & ComputerName & "\root\cimv2")
Set NIC = WMIService.ExecQuery("SELECT * FROM Win32_NetworkAdapter WHERE NetConnectionID = '" & ConnectionName & "'").ItemIndex(0)
if NIC is nothing then
WScript.Echo "NIC not found!"
WScript.quit
end if
WScript.Echo "NIC Current status: " & iif(NIC.NetEnabled, "Enabled", "Disabled") & vbcrlf
if NIC.NetEnabled then
WScript.Echo "Disabling NIC..."
NIC.Disable
WScript.Sleep 1000
WScript.Echo "Enabling NIC..."
NIC.Enable
end if
function iif(cond, truepart, falsepart)
if cond then iif=truepart else cond=falsepart
end function
function IsElevated()
On Error Resume Next
CreateObject("WScript.Shell").RegRead("HKEY_USERS\s-1-5-19\")
IsElevated = (err.number = 0)
end function
I'm running a web-based slideshow on multiple computer units. I have a VBScript that runs on startup, opens IE and navigates to a specific page in fullscreen mode. Everything works great, as long as there's an internet connection on startup. If there isn't then the page never loads. Is there a way in VBScript to check for a connection every couple minutes until the connection is found, and then continue with the script? Here is the code for your reference:
Option Explicit
Dim WshShell
set WshShell = WScript.CreateObject("WScript.Shell")
On Error Resume Next
With WScript.CreateObject ("InternetExplorer.Application")
.Navigate "http://www.example.com/slideshow"
.fullscreen = 1
.Visible = 1
WScript.Sleep 10000
End With
On Error Goto 0
Refer to this ==> Loop a function?
Yes, you can do it easily with this code :
Option Explicit
Dim MyLoop,strComputer,objPing,objStatus
MyLoop = True
While MyLoop = True
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
Call MyProgram()
wscript.quit
End If
Next
Pause(10) 'To sleep for 10 secondes
Wend
'**********************************************************************************************
Sub Pause(NSeconds)
Wscript.Sleep(NSeconds*1000)
End Sub
'**********************************************************************************************
Sub MyProgram()
Dim WshShell
set WshShell = WScript.CreateObject("WScript.Shell")
On Error Resume Next
With WScript.CreateObject ("InternetExplorer.Application")
.Navigate "http://www.example.com/slideshow"
.fullscreen = 1
.Visible = 1
WScript.Sleep 10000
End With
On Error Goto 0
End Sub
'**********************************************************************************************
If Hackoo's code doesn't work for you, you can try the following. Not all servers will respond to ping requests but you could just make an HTTP request and see if the server sends a valid response (status = 200).
Function IsSiteReady(strURL)
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", strURL, False
.SetRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.1)"
On Error Resume Next
.Send
If .Status = 200 Then IsSiteReady = True
End With
End Function
I am writing a vb script to monitor a process. The script monitors the status of a process and if the process is not running since 10 mins it should execute a command.Below is my script:
set objWMIService = GetObject ("winmgmts:")
foundProc = False
procName = "calc.exe"
Dim wshell
' Initialise the shell object to return the value to the monitor
Set wshell = CreateObject("WScript.Shell")
if err.number <> 0 then
WScript.Echo "Error: could not create WScript.Shell (error " & err.number & ", " & err.Description & ")"
WScript.quit(255)
end if
for each Process in objWMIService.InstancesOf ("Win32_Process")
If StrComp(Process.Name,procName,vbTextCompare) = 0 then
foundProc = True
procID = Process.ProcessId
End If
Next
#####code to check the proces status
If foundProc = True Then
WScript.Quit(0)
Else
WScript.sleep(1*60*1000)
If foundProc = True Then
WScript.Echo "Found Process (" & procID & ")"
Else
WScript.Echo "Process not running since 10 mins"
WScript.Quit(0)
End If
End If
Set WshShell = WScript.CreateObject("WScript.Shell")
Set objWMIService = GetObject("winmgmts:\\.\root\CIMV2")
Set objEvents = objWMIService.ExecNotificationQuery _
("SELECT * FROM Win32_ProcessTrace")
Do
Set objReceivedEvent = objEvents.NextEvent
If objReceivedEvent.ProcessName = "svchost.exe" then msgbox objReceivedEvent.ProcessName
' msgbox objReceivedEvent.ProcessName
Loop
You also have Win32_ProcessTraceStart and Win32_ProcessTraceStop. Above code is both.
It is also pointless doing error checking on WScript.Shell. It's a system component - it should be available. Also if it's not your script won't run as wscript isn't available to run your script.
I have a script that I put together for my users a few years ago for them to log onto to the company drive shares after they had logged into the VPN. The script has worked well over the years with a few tweaks needed here and there due to IE version upgrades. As of today I can no longer get the script to function properly the Error is:
Line: 93
Char: 5
Error: Permission denied: 'objIE.Document.parentWindow.screen'
Code: 800A0046
Source: Microsoft VBScript runtime error
I'm not sure what has changed but after doing multiple searches on the error codes and other items I figured I'd post it here and see if any of you can help me with this problem.
dim WshNetwork
Dim arrFileLines()
'On Error Resume Next
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.OpenTextFile("Drive Shares.txt", 1)
If Not err.number = 0 then
WScript.Echo "Drive Shares.txt was not found. Please ensure that it is in the same directory as this script file"
WScript.Quit
End If
NumElements = 0
Do Until objFile.AtEndOfStream
Redim Preserve arrFileLines(NumElements)
arrFileLines(NumElements) = objFile.ReadLine
NumElements = NumElements + 1
Loop
objFile.Close
strPw = GetPassword()
If strPw = "" Then
wScript.Quit
End If
SplitPasswd = Split(StrPW,"*",2)
username = "DEFAULT\" & SplitPasswd(0)
password = SplitPasswd(1)
Set WshNetwork = Wscript.CreateObject("WScript.Network")
For Count = 0 to (NumElements - 1)
SplitDriveInfo = Split(arrFileLines(Count)," ",2)
DriveLetter = SplitDriveInfo(0)
Share = SplitDriveInfo(1)
ExitCode = WshNetwork.MapNetworkDrive(DriveLetter, Share, false, username, password)
ErrorHandler(err.number)
Next
Sub ErrorHandler(ErrorNumber)
Select Case ErrorNumber
Case 0
'OK
Exit Sub
Case -2147024811
'Already Mapped Continue
Exit Sub
Case -2147024843
'No Connection
WScript.Echo "No connection found. Confirm you have an internet connection and that you have the VPN connected."
WScript.Quit
Case -2147024829
'Share not available
WScript.Echo "The drive share you are trying to connect to does not exist on this server."
WScript.Quit
Case -2147023570
'Invalid username or password
WScript.Echo "Invalid username or password. Please try again."
WScript.quit
Case Else
WScript.Echo "Unknown error: " & CStr(ErrorNumber)
WScript.Quit
End Select
End Sub
Function GetPassword()
Dim objIE
Set objIE = CreateObject( "InternetExplorer.Application" )
objIE.Navigate "about:blank"
objIE.Document.Title = "Login Credentials"
objIE.ToolBar = False
objIE.Resizable = False
objIE.StatusBar = False
objIE.Width = 320
objIE.Height = 320
With objIE.document.parentWindow.screen
objIE.Left = (.availwidth - objIE.Width ) \ 2
objIE.Top = (.availheight - objIE.Height) \ 2
End With
objIE.Document.Body.InnerHTML = "<DIV align=""center""><P>Please enter your credentials</P>" & vbCrLf _
& "<DIV align=""center""><P>Username</P>" & vbCrLf _
& "<P><INPUT TYPE=""Username"" SIZE=""20"" " _
& "ID=""UserName""></P>" & vbCrLf _
& "<DIV align=""center""><P>Password</P>" & vbCrLf _
& "<P><INPUT TYPE=""password"" SIZE=""20"" " _
& "ID=""Password""></P>" & vbCrLf _
& "<P><INPUT TYPE=""hidden"" ID=""OK"" " _
& "NAME=""OK"" VALUE=""0"">" _
& "<INPUT TYPE=""submit"" VALUE="" OK "" " _
& "OnClick=""VBScript:OK.Value=1""></P></DIV>"
objIE.Visible = True
Do While objIE.Document.All.OK.Value = 0
WScript.Sleep 200
Loop
GetPassword = objIE.Document.All.UserName.Value & "*" & objIE.Document.All.Password.Value
objIE.Quit
Set objIE = Nothing
End Function
Any help with this would be greatly appreciated.
Microsoft released hotfix:[KB3025390] http://support.microsoft.com/kb/3025390
I can confirm uninstalling this update will resolve issue if it worked just prior to December 17th, 2014.
I had a similar problem with an HTA program using IE 11 and the With objIE.Document.ParentWindow.Screen command.
I found adding objIE.left = 910 and objIE.top and removed the With objIE.Document.ParentWindow.Screen section and now the IE Windows opens fine.
Sub AdditionalComputerInfo
'v3.00 - Changed to HTML Output
strComputer = trim(txtComputerName.Value)
Set objIE = CreateObject("InternetExplorer.Application")
objIE.Navigate("about:blank")
objIE.ToolBar = 0
objIE.StatusBar = 0
objIE.addressbar = 0
objIE.Width = 650
objIE.Height = 900
'added v3.02
objIE.Left = 910
objIE.Top = 20
objIE.Document.Title = " " & uCase(strComputer) & " Information"
'With objIE.Document.ParentWindow.Screen removed in version 3.02
' objIE.Left = 910
' objIE.Top = 20
'End With
Set objDoc = objIE.Document.Body