VBS function not executing when button is selected - vbscript

I'm trying to make a VBScript that will allow me to select items from a drop down menu. If possible once an option is selected it will open a particular file or program. I'm not sure why it's not working? Any help would be very much appreciated.
Option Explicit
Dim objShell
Dim aOpt(6)
aOpt(0) = "Option 1"
aOpt(1) = "Option 2"
aOpt(2) = "Option 3"
aOpt(3) = "Option 4"
aOpt(4) = "Option 5"
aOpt(5) = " "
aOpt(6) = " "
SelectBox "Select an install option", aOpt
Function SelectBox(sTitle, aOptions)
Dim oIE, s, item
set oIE = CreateObject("InternetExplorer.Application")
With oIE
.ToolBar = False : .RegisterAsDropTarget = False
.StatusBar = False : .Navigate("about:blank")
While .Busy : WScript.Sleep 100 : Wend
With .document
With .parentWindow
if Instr(.navigator.appVersion, "MSIE 6") > 0 Then
oIE.FullScreen = True
End if
oIE.width = 400 : oIE.height = 600
oIE.left = .screen.width \ 2 - 200
oIE.top = .screen.height\ 2 - 75
End With ' ParentWindow
s = "<html><head><title>" & sTitle & " " & String(80, ".") _
& "</title></head><script language=vbs>bWait=true</script>" _
& "<body bgColor=Silver><center><b>" & sTitle & "<b><p>" _
& "<select id=entries size=1 style='width:250px'>" _
& " <option selected>" & sTitle & "</option>"
For each item in aOptions
s = s & " <option>" & item & "</option>"
Next
s = s & " </select><p>" _
& "<button id=but0 onclick='bWait=false'>OK</button>" _
& "</center></body></html>"
.WriteLn(s)
With .body
.scroll="no"
.style.borderStyle = "outset"
.style.borderWidth = "3px"
End With ' Body
.all.entries.focus
oIE.Visible = True
On Error Resume Next
While .ParentWindow.bWait
WScript.Sleep 100
if oIE.Visible Then SelectBox = ""
if Err Then Exit Function
Wend ' Wait
On Error Goto 0
With .ParentWindow.entries
SelectBox = .options(.selectedIndex).text
End With
End With ' document
.Visible = False
End With ' IE
Set objShell = WScript.CreateObject( "WScript.shell" )
If aOptions = aOpt(0) Then
objShell.Run("""Z:\folder\file""")
Set objShell = Nothing
End if
End Function

"It's not working" because
If aOptions = aOpt(0) Then
compares an array against an element of an other (?) array. By rights you should get an error message:
>> aOptions = Array()
>> If aOptions = "whatever" Then
>> WScript.Echo "bingo"
>> End If
>>
Error Number: 13
Error Description: Type mismatch
If not, you have disabled VBScript's error handling.

Related

Unable to pin .exe with parameter to Taskbar/Start Menu

I'm trying to write a .vbs script to pin an .exe to my taskbar and start menu.
However, the .exe will only run if I pass in a package parameter.
Here's the target of the shortcut:
"C:\Program Files (x86)\Launch\AppLauncher.exe" package=TEST
I currently have the following for code but I get the error message attached when I try and run it.
Const a = """"
arrActions = Array( _
"pin", "Start Menu", """C:\Program Files (x86)\Launch\AppLauncher.exe"" package=TEST", _
"pin", "Taskbar", """C:\Program Files (x86)\Launch\AppLauncher.exe"" package=TEST" _ )
For intAction = 0 To (UBound(arrActions) - 2) Step 3
arrFileNames = Array(arrActions(intAction + 2))
'strMode can be "Pin" or "Unpin"
strMode = arrActions(intAction)
'strLocation can be "Start Menu" or "Taskbar" or "Both"
strLocation = arrActions(intAction + 1)
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objShellApp = CreateObject("Shell.Application")
Set objShell = CreateObject("WScript.Shell")
If LCase(strLocation) = "both" Then
arrLocations = Array("Start Menu", "Taskbar")
Else
arrLocations = Array(strLocation)
End If
For Each strLocation In arrLocations
If LCase(strMode) <> "pin" And LCase(strMode) <> "unpin" Then
WScript.Echo "Mode is incorrect. Please set to ""pin"" or ""unpin""."
WScript.Quit
ElseIf LCase(strLocation) <> "start menu" And LCase(strLocation) <> "taskbar" Then
WScript.Echo "Location is incorrect. Please set to ""Start Menu"" or ""Taskbar""."
WScript.Quit
Else
strMode = LCase(strMode)
If strMode = "pin" Then
strVerb = LCase(strMode & " to " & strLocation)
strMessage = " has been " & strMode & "ned to the " & strLocation & "."
ElseIf strMode = "unpin" Then
strVerb = LCase(strMode & " from " & strLocation)
strMessage = " has been " & strMode & "ned from the " & strLocation & "."
End If
For Each strFilePath In arrFileNames
If LCase(strFilePath) = "unpin_all" And strMode = "unpin" Then
strPinLocation = objShell.ExpandEnvironmentStrings("%APPDATA%") & _
"\Microsoft\Internet Explorer\Quick Launch\User Pinned\" & _
Replace(strLocation, " ", "") & "\"
For Each objFile In objFSO.GetFolder(strPinLocation).Files
strFullPath = objFile.Path
'Set objFile = objFSO.GetFile(objFile.Path)
Set objFolder = objShellApp.Namespace(objFile.ParentFolder & "\")
Set objFolderItem = objFolder.ParseName(objFile.Name)
Set colVerbs = objFolderItem.Verbs
For Each objVerb In colVerbs
If LCase(Replace(objVerb.name, "&", "")) = strVerb Then
objVerb.DoIt
WScript.Echo strFullPath & strMessage
End If
Next
Next
Else
If objFSO.FileExists(strFilePath) = True Then
Set objFile = objFSO.GetFile(strFilePath)
Set objFolder = objShellApp.Namespace(objFile.ParentFolder & "\")
Set objFolderItem = objFolder.ParseName(objFile.Name)
Set colVerbs = objFolderItem.Verbs
blnOptionFound = False
For Each objVerb In colVerbs
If LCase(Replace(objVerb.name, "&", "")) = strVerb Then
objVerb.DoIt
blnOptionFound = True
End If
Next
If blnOptionFound = True Then
WScript.Echo strFilePath & strMessage
Else
WScript.Echo "Unable to " & strMode & " " & strFilePath & _
" from the " & strLocation & ". The verb does not exist."
End If
Else
WScript.Echo "Could not find " & strFilePath
End If
End If
Next
End If
Next
Next
Error message

VB script to scan latest log file for errors

I have a VB script which scans the mentioned log file for errors and sends a notification through an email.
How can I scan the latest log file in the folder? For example, Filename1.070615 (Filename1.mmddyy) is a log file. After a certain size, the logfile switches to new file with the same name but different date: Filename1.070615.
cdoSendUsingPort = 2, _
Const ForReading = 1
Dim intStartAtLine, strFileCreateddate, i, strResults, strTextToScanFor, bStartFromScratch
Dim strLastCheckedFor, strArrayToString, strSubject, strMailFrom, strMailTo
strMailto = "<Emailaddress>"
strMailFrom = "<FromAddress>"
strSubject = "Log scanner"
strSMTPServer = "x.x.x.x"
FileToRead = "D:\LOG\filename1.mmddyy"
arrTextToScanFor = Array("error","another thing")
Set WshShell = WScript.CreateObject("WScript.Shell")
searchkey = replace(replace(filetoread,":",""),"\","_")
On Error Resume Next
strLastFileCheckedCreateDate = WshShell.RegRead("HKCU\Software\RDScripts\CheckTXTFile\" & searchkey & "\CreateDate")
strLastFileLastLineChecked = WshShell.RegRead("HKCU\Software\RDScripts\CheckTXTFile\" & searchkey & "\LastLineChecked")
strLastCheckedFor = WshSHell.RegRead("HKCU\Software\RDScripts\CheckTXTFile\" & searchkey & "\CheckForString")
iLastCheckedLine = WshSHell.RegRead("HKCU\Software\RDScripts\CheckTXTFile\" & searchkey & "\LastLineChecked")
On Error GoTo 0
Set objFSO = WScript.CreateObject("Scripting.FileSystemObject")
Set varFile = objFSO.GetFile(FileToRead)
arrLastCheckedForText = split(strLastCheckedFor,",")
strFileCreateDate = varfile.datecreated
strFileModifiedDate = varfile.datelastmodified
sStatus = "<li>Using mail server: " & strSMTPServer & "</li><li>Running from: " & wscript.scriptfullname & "</li>"
Set objTextFile = objFSO.OpenTextFile(FileToRead, ForReading)
objTextFile.ReadAll
iLineCount = objTextFile.Line
objTextFile.close
If strLastCheckedFor = "" Then
bStartFromScratch = true
sStatus = sStatus & "<li>First run of script against string search</li>" & vbcrlf
ElseIf ubound(arrTextToScanFor) <> ubound(arrLastCheckedForText) Then
bStartFromScratch = true
sStatus = sStatus & "<li>Count of string search criteria has changed</li>" & vbcrlf
Else
For each strItem in arrTextToScanFor
Else
bStartFromScratch = true
'MsgBox strResults
End If
If bStartFromScratch = true Then
sStatus = sStatus & "<li>String search criteria does not match prior search</li>" & vbcrlf
End If
Next
End If
If cint(iLineCount) < cint(iLastCheckedLine) Then
bStartFromScratch = true
sStatus = sStatus & "<li>Last line checked (" & iLastCheckedLine & ") is greater than total line count (" & iLineCount & ") in file</li>"
End If
If CStr(strFileCreateDate) = CStr(strLastFileCheckedCreateDate) and bStartFromScratch <> true Then
intStartAtLine = strLastFileLastLineChecked
If bStartFromScratch <> true then
sStatus = sStatus & "<li>Continuing search from line " & intStartAtLine & "</li>" & vbcrlf
End If
ElseIf strFileCreateDate <> strLastFileCheckedCreateDate or bStartFromScratch = true Then
intStartAtLine = 0
If bStartFromScratch <> true then
sStatus = sStatus & "<li>File created date has changed, starting search from line 0</li>" & vbcrlf
End If
End If
i = 0
Dim strNextLine
For each strItem in arrTextToScanFor
strArrayToString = strArrayToString & delim & strItem
delim = ","
Next
Set objTextFile = objFSO.OpenTextFile(FileToRead, ForReading)
Do While objTextFile.AtEndOfStream <> True
If i < CInt(intStartAtLine) Then
objTextFile.skipline
Else
'MsgBox i
strNextLine = objTextFile.Readline
For each strItem in arrTextToScanFor
If InStr(LCase(strNextLine),LCase(strItem)) Then
strResults = "<span style='font-family:courier-new;color:#696969'><span style='font-weight:bold;background-color:#BEF3F3'>Line " & i & ":</span> " & replace(lcase(strNextLine),lcase(strItem),"<span style='background-color:#FFFF81'>" & strItem & "</span>") & "</span><br>" & vbcrlf & strResults
bSendMail = true
End If
Next
End If
i = i + 1
Loop
objTextFile.close
Set WshShell = CreateObject("WScript.Shell")
'Let's save our settings for next time.
WshShell.RegWrite "HKCU\Software\RDScripts\CheckTXTFile\" & searchkey & "\FileChecked", FileToRead, "REG_SZ"
WshShell.RegWrite "HKCU\Software\RDScripts\CheckTXTFile\" & searchkey & "\CreateDate", strFileCreateDate, "REG_SZ"
WshShell.RegWrite "HKCU\Software\RDScripts\CheckTXTFile\" & searchkey & "\LastLineChecked", i, "REG_SZ"
WshShell.RegWrite "HKCU\Software\RDScripts\CheckTXTFile\" & searchkey & "\LastScanned", Now, "REG_SZ"
WshShell.RegWrite "HKCU\Software\RDScripts\CheckTXTFile\" & searchkey & "\CheckForString",strArrayToString, "REG_SZ"
set WshShell = nothing
strFileSummary = "<tr><td style='font-family:calibri;font-weight:bold;color:darkblue;width:200px'>File path:</td><td>" & FileToRead & "</td></tr>"
strFileCreateDateSummary = "<tr><td style='font-family:calibri;font-weight:bold;color:darkblue;width:200px'>Created date:</td><td>" & strFileCreateDate & "</td></tr>"
strFileModifiedDateSummary = "<tr><td style='font-family:calibri;font-weight:bold;color:darkblue;width:200px'>Modified date:</td><td>" & strFileModifiedDate & "</td></tr>"
strArraySummary = "<tr><td style='font-family:calibri;font-weight:bold;color:darkblue;width:200px'>Text string(s):</td><td>" & strArrayToString & "</td></tr>"
strFileLineSummary = "<tr><td style='font-family:calibri;font-weight:bold;color:darkblue;width:200px'>Last line checked:</td><td>" & i & "</td></tr>"
strSummary = strFileSummary & strFileCreateDateSummary & strFileModifiedDateSummary & strArraySummary & strFileLineSummary
strBodyContent = "<table style='font-family:calibri;'>" & strSummary & "</table><br><br><span style='font-size:large;'>Entries:</span><br>" & strResults & "<div style='padding-top:30px;font-size:x-small'><br><div style='font-weight:bold;font-family:calibri;color:black;'>Job Details:<ul style='font-weight:normal;font-family:calibri;color:darkgray;'>" & sStatus & "</ul></div></div>"
on error goto 0
'Send the email if need be.
If bSendMail = true Then Call sendmail(strMailFrom,strMailTo,strSubject,strBodyContent)
'------------------------------------------------------------------------
'Function EmailFile - email the warning file
'------------------------------------------------------------------------
Function SendMail(strFrom,strTo,strSubject,strMessage)
Dim iMsg, iConf, Flds
On Error GoTo 0
'// Create the CDO connections.
Set iMsg = CreateObject("CDO.Message")
Set iConf = CreateObject("CDO.Configuration")
Set Flds = iConf.Fields
'// SMTP server configuration.
With Flds
.Item(cdoSendUsingMethod) = cdoSendUsingPort
'// Set the SMTP server address here.
.Item(cdoSMTPServer) = strSMTPServer
.Update
End With
'// Set the message properties.
With iMsg
Set .Configuration = iConf
.To = strMailTo
.From = strMailFrom
.Subject = strSubject
.htmlbody = strMessage
End With
'iMsg.HTMLBody = strMessage
'// Send the message.
iMsg.Send ' send the message.
If CStr(err.number) <> 0 Then
Else
End If
End Function
It would be a bit easier if your log files were named filename1.yymmdd.
Nevertheless, we can use a regex to not only verify the filename but also swap the date components to put them in our desired format!
Set re = New RegExp
re.Pattern = "^(filename1\.)(\d{2})(\d{2})(\d{2})$"
Set fso = CreateObject("Scripting.FileSystemObject")
For Each objFile In fso.GetFolder("d:\log").Files
If re.Test(objFile.Name) Then
strCompareName = re.Replace(objFile.Name, "$1$4$2$3")
If strCompareName > strLatest Then strLatest = strCompareName
End If
Next
' Switch the name back...
strLatest = re.Replace(strLatest, "$1$3$4$2")
WScript.Echo "The latest file is: " & strLatest
This line:
strCompareName = re.Replace(objFile.Name, "$1$4$2$3")
changes the format from mmddyy to yymmdd and saves it in a string for comparison.
Once we've finished our comparisons, we just need to take the latest file we found and reverse the process:
strLatest = re.Replace(strLatest, "$1$3$4$2")
to get the original filename back!

How to Make a VBScript Timer

I need to have a timer appear in a message box, coded in vbs. The message box needs to be in the bottom left corner of the screen, just above the start menu. It needs to not be able to exit, meaning it cannot be listed on the task bar (hopefully) and have no minimise/exit buttons. It needs to stay on top of all the other windows. It also needs to start at 20 minutes, counting down in seconds. I hope someone can help me with this - it's for a computer lab.
Thanks,
Matthew
Try something like that :
Option Explicit
Dim Title,ws,nMinutes,nSeconds,sMessage
Title = "Counting Down to Shutdown"
Set ws = CreateObject("wscript.Shell")
nMinutes = 20
nSeconds = 0
sMessage = "<font color=Red size=2><b>Counting Down to Shutdown"
'Open a chromeless window with message
with HTABox("lightBlue",100,250,0,630)
.document.title = "Counting Down Notification to Shutdown"
.msg.innerHTML = sMessage
do until .done.value or (nMinutes + nSeconds < 1)
.msg.innerHTML = sMessage & "<br>" & nMinutes & ":" & Right("0"&nSeconds, 2) _
& " remaining</b></font><br>"
wsh.sleep 1000 ' milliseconds
nSeconds = nSeconds - 1
if nSeconds < 0 then
if nMinutes > 0 then
nMinutes = nMinutes - 1
nSeconds = 59
end if
end if
loop
.done.value = true
.close
end with
ws.Popup "TIME IS OVER !","5",Title,0+48 'Afficher un Popup durant 5 secondes puis on quitte le script
'Command="cmd /c Shutdown.exe -s -t 30 -c " & DblQuote("Sauvegarder votre Travail car l'ordinateur va rebooter dans 30 secondes")
'Executer = WS.Run(Command,0,False)
'*****************************************************************
Function HTABox(sBgColor, h, w, l, t)
Dim IE, HTA, sCmd, nRnd
randomize : nRnd = Int(1000000 * rnd)
sCmd = "mshta.exe ""javascript:{new " _
& "ActiveXObject(""InternetExplorer.Application"")" _
& ".PutProperty('" & nRnd & "',window);" _
& "window.resizeTo(" & w & "," & h & ");" _
& "window.moveTo(" & l & "," & t & ")}"""
with CreateObject("WScript.Shell")
.Run sCmd, 1, False
do until .AppActivate("javascript:{new ") : WSH.sleep 10 : loop
end with 'WSHShell
For Each IE In CreateObject("Shell.Application").windows
If IsObject(IE.GetProperty(nRnd)) Then
set HTABox = IE.GetProperty(nRnd)
IE.Quit
HTABox.document.title = "HTABox"
HTABox.document.write _
"<HTA:Application contextMenu=no border=thin " _
& "minimizebutton=no maximizebutton=no sysmenu=no SHOWINTASKBAR=no >" _
& "<body scroll=no style='background-color:" _
& sBgColor & ";font:normal 10pt Arial;" _
& "border-Style:inset;border-Width:3px'" _
& "onbeforeunload='vbscript:if not done.value then " _
& "window.event.cancelBubble=true:" _
& "window.event.returnValue=false:" _
& "done.value=true:end if'>" _
& "<input type=hidden id=done value=false>" _
& "<center><span id=msg> </span><br>" _
& "<input type=button id=btn1 value=' OK ' "_
& "onclick=done.value=true><center></body>"
HTABox.btn1.focus
Exit Function
End If
Next
MsgBox "HTA window not found."
wsh.quit
End Function
'*****************************************************************

Permission Denied Error 800A0046 'objIE.Document.parentWindow.screen'

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

Looking for a way to load url in new tab and change the title once done

I am able to load url on NEW window and change the web title with the following:
Set IE = CreateObject("InternetExplorer.Application")
set WshShell = WScript.CreateObject("WScript.Shell")
IE.Navigate "http://www.google.com"
IE.Visible = True
While IE.Busy
Wend
While IE.Document.ReadyState <> "complete"
Wend
IE.Document.Title = "yoyo"
Is there any way to make it open new tab instead of new window? How?
Another senarion I am trying is with:
set WshShell = WScript.CreateObject("WScript.Shell")
url= "http://google.com/"
Set objShell = CreateObject("Wscript.Shell")
objShell.Run(url)
IE.document.title = "yoyo"
This allow me to open new tabs on the same browser (IE) but I cannot change the page title...
Any help will be highly appreciated!
Look here:
' VB Script Document
' http://stackoverflow.com/questions/22821984/looking-for-a-way-to-load-url-in-new-tab-and-change-the-title-once-done
'
option explicit
On Error Goto 0
Dim strMyUrl : strMyUrl = "http://www.avg.com" 'strMyUrl = "http://www.jysk.cz" 'strMyUrl = "https://www.google.cz" 'strMyUrl = "www.microsoft.com"
Dim strWTitle : strWTitle = "yoyo"
Dim strResult : strResult = WScript.ScriptName '
Dim WshShell : Set WshShell = WScript.CreateObject( "WScript.Shell")
Dim IE : Set IE = Nothing
Dim oIE : Set oIE = Nothing
Dim intWExist, BrowserNavFlag, intButton, sRetVal
intWExist = FindIE( strMyUrl, oIE) 'look for MSIE window'
set IE = oIE
Select Case intWExist
Case 3
''' MSIE window found, URL match, window title match
''' (not implemented yet)
Case 2
''' MSIE window found, URL match
Case 1
''' MSIE window found, no URL match
''' BrowserNavFlag = 65536 ' navOpenNewForegroundTab
BrowserNavFlag = 2048 ' navOpenInNewTab
IE.Navigate2 strMyUrl, CLng( BrowserNavFlag), "_blank"
Case Else
''' MSIE window not found
Set IE = CreateObject( "InternetExplorer.Application")
BrowserNavFlag = 1
IE.Navigate strMyUrl ', CLng( BrowserNavFlag)
End Select
IE.Visible = True
While IE.Busy
Wscript.Sleep 100
Wend
While IE.Document.ReadyState <> "complete" 'Or IE.ReadyState <> 4
Wscript.Sleep 100
Wend
'intButton = WshShell.Popup( "watch how MSIE title change", 1)
If intWExist <> 1 Then
intWExist = 2
Else
Set oIE = Nothing
Set IE = Nothing
strResult = strResult & vbNewLine & vbTab & "FindIE() pass # 2"
Wscript.Sleep 2000 'additional time for the Navigate2 method'
intWExist = FindIE( strMyUrl, oIE) 'get right object for newly created tab'
If intWExist = 2 Then
set IE = oIE
End If
End If
If intWExist = 2 Then
IE.Document.Title = strWTitle
sRetVal = "done"
Else
sRetVal = "'IE.Document.Title = strWTitle' - not renamed"
End If
Set IE = Nothing
Wscript.Echo strResult & vbNewLine & sRetVal ' propagate result
Private Function FindIE( ByVal sUrl, ByRef oObj)
' parameters
' sUrl (input) string
' oObj (output) object
' returns
' 0 = any MSIE window not found - or found but not accessible
' 1 = a MSIE window found
' 2 = 1 and address line match
' 3 = 2 and title match (not implemented yet)
Dim ww, tpnm, tptitle, tpfulln, tpUrl, tpUrlUnencoded
Dim errNo, errStr, intLoop, intLoopLimit
Dim iFound : iFound = 0
Dim shApp : Set shApp = CreateObject( "shell.application")
With shApp
For Each ww In .windows
tpfulln = ww.FullName
strResult = strResult & vbNewLine & ww.Application & vbTab & tpfulln
If Instr( 1, Lcase( tpfulln), "iexplore.exe", 1) <> 0 Then
If iFound > 0 Then
Else
Set oObj = ww
End If
tptitle = "x x x" : tpUrl = "" : tpUrlUnencoded = ""
intLoopLimit = 100 ' to look for attributes max. intLoopLimit/10 seconds
intLoop = 0
While intLoop < intLoopLimit
intLoop = intLoop + 1
On Error Resume Next
tpnm = typename( ww.document)
errNo = Err.Number
If errNo <> 0 Then
'error if page not response (yet)'
errStr = "Error # " & CStr( errNo) & " " & Err.Description
Wscript.Sleep 100
Else
iFound = 1
intLoopLimit = intLoop ' end While..Wend loop and preserve loop counter
tptitle = ww.document.title
tpUrl = ww.document.URL
tpUrlUnencoded = ww.document.URLUnencoded
errStr = tpnm
End If
On Error Goto 0
Wend
strResult = strResult & vbTab & errStr & " " & CStr( intLoop)
If Instr( 1, Lcase( tpnm), "htmldocument", 1) <> 0 then
strResult = strResult & vbTab & tptitle _
& vbNewLine & vbTab & tpUrl _
'& vbNewLine & vbTab & tpUrlUnencoded
If Instr( 1, Lcase( tpUrl), Lcase( sUrl), 1) <> 0 Then
Set oObj = ww
iFound = 2
strResult = strResult & vbTab & "!match!"
' looking for all matching MSIE URLs
' this may take considerable time amount
' to speed up script running, uncomment next line "exit for"
' exit for
Else
End If
End If
Else
' a program reports the same shell.application property as "iexplore.exe"
' i.e. "explorer.exe"
' i.e. "HTML preview" in some editors
' etc.
End If
Next
End With
Set shApp = Nothing
strResult = strResult & vbNewLine & Cstr( iFound)
FindIE = iFound
End Function

Resources