Accented french characters in a msgbox - vbscript

I am trying to write a vbscript that uses Google speech to the pronunciation of a message.
I have to save the code into notepad ++ with UTF8 encoding without BOM and pronunciation is good, but the display of the message box is not good for accented characters.
How to solve this problem ?
Thank you!
Option Explicit
Call Ip_Publique()
'***********************************************************************************************************************************************************
Sub Ip_Publique()
Dim Titre,URL,ie,objFSO,Data,OutPut,objRegex,Match,Matches,ip_public
Dim Message,URLFR
Message = "Vous êtes connecté à internet !" & VbCrlf & "Votre IP Publique est : "
URLFR = "http://translate.google.com/translate_tts?ie=UTF-8&tl=fr&q=" & Message
Titre = "Adresse Ip Publique !"
URL = "http://monip.org"
If OnLine("smtp.gmail.com") = True Then
Set ie = CreateObject("InternetExplorer.Application")
Set objFSO = CreateObject("Scripting.FileSystemObject")
ie.Navigate (URL)
ie.Visible=False
DO WHILE ie.busy
Wscript.Sleep 100
Loop
Data = ie.document.documentElement.innertext
Set objRegex = new RegExp
objRegex.Pattern = "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b"
objRegex.Global = False
objRegex.IgnoreCase = True
Set Matches = objRegex.Execute(Data)
For Each Match in Matches
Call Kill("wmplayer.exe")
Call WmPlaySound(URLFR & Match.Value)
MsgBox Message & Match.Value,64,Titre
Pause(10)
Call Kill("wmplayer.exe")
Next
ie.Quit
Set ie = Nothing
Else
MsgBox "Vérifier votre connexion internet puis re-executer ce script",48,Titre
Exit Sub
End If
End Sub
'************************************************************************************************************************************************************
Function OnLine(strHost)
Dim objPing,z,objRetStatus,PingStatus
Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery("select * from Win32_PingStatus where address = '" & strHost & "'")
z = 0
Do
z = z + 1
For Each objRetStatus In objPing
If IsNull(objRetStatus.StatusCode) Or objRetStatus.StatusCode <> 0 Then
PingStatus = False
Else
PingStatus = True
End If
Next
Call Pause(1)
If z = 4 Then Exit Do
Loop until PingStatus = True
If PingStatus = True Then
OnLine = True
Else
OnLine = False
End If
End Function
'*********************************************************************************************
'Fonction pour ajouter les doubles quotes dans une variable
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'**********************************************************************************************
Sub WmPlaySound(MySound)
Dim WshShell
Set WshShell = CreateObject("WScript.Shell")
WshShell.Run "wmplayer "& DblQuote(MySound) &"",0,False
Set WshShell = Nothing
End Sub
'**********************************************************************************************
Sub Kill(Process)
Dim Ws,Command,Execution
Set Ws = CreateObject("WScript.Shell")
Command = "cmd /c Taskkill /F /IM "&Process&""
Execution = Ws.Run(Command,0,True)
End Sub
'**********************************************************************************************
Sub Pause(NSeconds)
Wscript.Sleep(NSeconds*1000)
End Sub
'**********************************************************************************************

OK, i solved it like this and you can give a try and post me your feed back.
The script is saved as ANSI and it worked well for me.
Description :
This script will display three messages box with 3 different languages ​​with Google Voice Speech.
English
French
Arabic
Option Explicit
Call Ip_Publique()
'***********************************************************************************************************************************************************
Sub Ip_Publique()
Dim Titre,URL,ie,objFSO,Data,OutPut,objRegex,Match,Matches,ip_public,IP
Dim MessageEN,MessageFR,MessageAR,URLEN,URLFR,URLAR,Copyright
Copyright = "(2014 © Hackoo)"
MessageEN = "You are connected to the internet !" & VbCrlf & "Your Public IP Adress is "
MessageFR = "Vous êtes connecté à internet !" & VbCrlf & "Votre IP Publique est "
MessageAR = ChrW(1571)&ChrW(1606)&ChrW(1578)&ChrW(32)&ChrW(1605)&ChrW(1578)&ChrW(1589)&ChrW(1604)&_
ChrW(32)&ChrW(1576)&ChrW(1588)&ChrW(1576)&ChrW(1603)&ChrW(1577)&ChrW(32)&ChrW(1575)&ChrW(1604)&ChrW(1573)&_
ChrW(1606)&ChrW(1578)&ChrW(1585)&ChrW(1606)&ChrW(1578)& VbCrlf & "IP "
URLEN = "http://translate.google.com/translate_tts?tl=en&q=" & MessageEN
URLFR = "http://translate.google.com/translate_tts?tl=fr&q=" & MessageFR
URLAR = "http://translate.google.com/translate_tts?ie=UTF-8&tl=ar&q=" & MessageAR
Titre = "Adresse IP Publique " & Copyright
URL = "http://monip.org"
If OnLine("smtp.gmail.com") = True Then
Set ie = CreateObject("InternetExplorer.Application")
Set objFSO = CreateObject("Scripting.FileSystemObject")
ie.Navigate (URL)
ie.Visible=False
DO WHILE ie.busy
Wscript.Sleep 100
Loop
Data = ie.document.documentElement.innertext
Set objRegex = new RegExp
objRegex.Pattern = "\b([0-9]{1,3}\.){3}[0-9]{1,3}\b"
objRegex.Global = False
objRegex.IgnoreCase = True
Set Matches = objRegex.Execute(Data)
For Each Match in Matches
IP = Match.Value
Call NavigateIE(URLEN & IP)
MsgBox MessageEN & IP,64,Titre
Call NavigateIE(URLFR & IP)
MsgBox MessageFR & IP,64,Titre
Call NavigateIE(URLAR & IP)
MsgBox MessageAR & IP,64,Titre
Next
ie.Quit
Set ie = Nothing
Else
MsgBox "Vérifier votre connexion internet puis re-executer ce script",48,Titre
Exit Sub
End If
End Sub
'************************************************************************************************************************************************************
Function OnLine(strHost)
Dim objPing,z,objRetStatus,PingStatus
Set objPing = GetObject("winmgmts:{impersonationLevel=impersonate}").ExecQuery("select * from Win32_PingStatus where address = '" & strHost & "'")
z = 0
Do
z = z + 1
For Each objRetStatus In objPing
If IsNull(objRetStatus.StatusCode) Or objRetStatus.StatusCode <> 0 Then
PingStatus = False
Else
PingStatus = True
End If
Next
Call Pause(1)
If z = 4 Then Exit Do
Loop until PingStatus = True
If PingStatus = True Then
OnLine = True
Else
OnLine = False
End If
End Function
'*********************************************************************************************
'Fonction pour ajouter les doubles quotes dans une variable
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'**********************************************************************************************
Sub Pause(NSeconds)
Wscript.Sleep(NSeconds*1000)
End Sub
'**********************************************************************************************
Sub NavigateIE(URL)
Dim objExplorer
Set objExplorer = CreateObject("InternetExplorer.Application")
with objExplorer
.Navigate(URL)
.Visible = False
end with
End Sub
'**********************************************************************************************

Related

VBScript RegEx : Replace Content

I want to update the Unbound_DNS configuration file from a raw source but I can not get the desired result.
I would like to format each entry (each line):
address=/abc.com/0.0.0.0
To
local-zone: "abc.com" redirect
local-data: "abc.com 86400 IN A 0.0.0.0"
Here is what I did (thanks to hackoofr):
Option Explicit
Dim URL,Save2File,ws
If Not WScript.Arguments.Named.Exists("elevate") Then
CreateObject("Shell.Application").ShellExecute WScript.FullName _
, """" & WScript.ScriptFullName & """ /elevate", "", "runas", 1
WScript.Quit
End If
URL = "https://raw.githubusercontent.com/notracking/hosts-blocklists/master/domains.txt"
Set ws = CreateObject("wscript.Shell")
Save2File = ws.ExpandEnvironmentStrings("%Windir%\Temp\test")
Call Download(URL,Save2File)
'**********************************************************************************************
Sub Download(URL,Save2File)
Dim File,Line,BS,ws,RegExp
On Error Resume Next
Set File = CreateObject("MSXML2.XMLHTTP")
File.Open "GET",URL, False
File.Send
If err.number <> 0 then
Line = Line & vbcrlf & "Error Getting File"
Line = Line & vbcrlf & "Error " & err.number & "(0x" & hex(err.number) & ") " & vbcrlf &_
err.description
Line = Line & vbcrlf & "Source " & err.source
MsgBox Line,vbCritical,"Error getting file"
Err.clear
wscript.quit
End If
If File.Status = 200 Then
'**********************************************************************************************
' Replace content for use with the file service.conf of soft Unbound_DNS
'
' address=/abc.com/0.0.0.0 to local-zone: "abc.com" redirect
' local-data: "abc.com 3600 IN A 0.0.0.0"
'**********************************************************************************************
Set RegExp = CreateObject("VBScript.RegExp")
RegExp.IgnoreCase = True
RegExp.Global = True
RegExp.Pattern = "address=/(.*)/([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})"
File.ResponseBody = RegExp.Replace(File.ResponseBody, "local-zone: \""$1\"" redirect $1" & ret & ">local-data: \""$1 3600 IN A $2\""")
Set RegExp = Nothing
'**********************************************************************************************
' Write content
'**********************************************************************************************
Set BS = CreateObject("ADODB.Stream")
Set ws = CreateObject("wscript.Shell")
BS.type = 1
BS.open
BS.Write File.ResponseBody
BS.SaveToFile Save2File, 2
'**********************************************************************************************
' Clean cache DNS
'**********************************************************************************************
wshShell.run("cmd /c psexec \\ -s ipconfig /flushdns >> & hostName,TRUE")
ElseIf File.Status = 404 Then
MsgBox "UpdateHostname.vbs : File Not Found : " & File.Status,vbCritical,"UpdateHostname.vbs : Error File Not Found"
Else
MsgBox "UpdateHostname.vbs : Unknown Error : " & File.Status,vbCritical,"UpdateHostname.vbs : Error getting file"
End If
End Sub
'**********************************************************************************************
Thank you in advance for your help.
Edit 1:
The content does not change. File.ResponseBody returns the content correctly, but no modification by the regexp!
Replace the following code:
Set RegExp = CreateObject("VBScript.RegExp")
RegExp.IgnoreCase = True
RegExp.Global = True
RegExp.Pattern = "address=/(.*)/([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})"
File.ResponseBody = RegExp.Replace(File.ResponseBody, "local-zone: \""$1\"" redirect $1" & ret & ">local-data: \""$1 3600 IN A $2\""")
Set RegExp = Nothing
with this:
Dim objReg, strTest, objMatches, objMatch
Set objReg = New RegExp
strTest = File.ResponseBody 'address=/abc.com/0.0.0.0
objReg.Global = True
objReg.Pattern = "address=/(.*?)/(\d{1,3}(?:\.\d{1,3}){3})" 'abc.com gets stored in Group 1 and the IP address gets stored in Group 2
Set objMatches = objReg.Execute(strTest)
For Each objMatch In objMatches
strTest = "local zone: """ & objMatch.Submatches.Item(0) & """ redirect" & vbCrLf &_
"local data: """ & objMatch.Submatches.Item(0) & " 86400 in A " & objMatch.Submatches.Item(1)&""""
Next
File.ResponseBody = strTest
set objReg = Nothing
Click for Regex Demo(in the demo, / is escaped by \)
Regex Explanation:
address=/(.*?)/(\d{1,3}(?:\.\d{1,3}){3})
address=/ - matches address=/ literally
(.*?) - matches 0+ occurrences of any character(except a newline), as few as possible. The parenthesis are used to capture this match as group 1
/ - matches / literally
(\d{1,3}(?:\.\d{1,3}){3}) - matches a string of the pattern 12.222.212.33 and captures it in Group 2
Update:
Here is my final solution. From what I could understand from your code, you first get the response body from the server, modify and store the updated response in a file called test in the temp folder. Below is the code I have written to do the same thing. I have tested it on my system and the final output which gets stored in the C:\Windows\Temp\test.txt file looks correct as shown in the attached screenshot. Now, this may not be exactly what you want but you can get an idea from this. Store this code in a new vbs file and run it directly as it is.
Note: Since the response text from the server is very long, It takes a bit long to get executed. If you just want to see if it is working or not, uncomment the code inside the for loop. You will be able to see that you are getting the desired result for the first few URLs
Regex Demo
Option Explicit
Dim File, objReg, strTest, objMatches, objMatch, saveToFile, fso, outFile, strReplace, objShell, i
Set objShell = CreateObject("wscript.shell")
saveToFile = objShell.ExpandEnvironmentStrings("%windir%\Temp\test.txt")
Set File = CreateObject("MSXML2.XMLHTTP")
File.Open "GET","https://raw.githubusercontent.com/notracking/hosts-blocklists/master/domains.txt", False
File.send
If File.Status = 200 Then
Set objReg = New RegExp
strTest = File.responseText 'address=/abc.com/0.0.0.0
objReg.Global = True
objReg.Pattern = "address=/(.*?)/(\d{1,3}(?:\.\d{1,3}){3})" 'abc.com gets stored in Group 1 and the IP address gets stored in Group 2
Set objMatches = objReg.Execute(strTest)
For Each objMatch In objMatches
strReplace = "local zone: """ & objMatch.Submatches.Item(0) & """ redirect" & vbCrLf &_
"local data: """ & objMatch.Submatches.Item(0) & " 86400 in A " & objMatch.Submatches.Item(1)&"""" & vbCrLf
strTest = Replace(strTest,objMatch.Value,strReplace)
'Uncomment the following code to see the result for the 1st 5 URLs, if the whole thing is taking too long to get executed
'i=i+1
'If(i>5) Then
' Exit for
'End If
Next
set objReg = Nothing
'**********************************************************************************************
' Write content
'**********************************************************************************************
Set fso = CreateObject("scripting.filesystemobject")
Set outFile = fso.OpenTextFile(saveToFile,2,True)
outFile.Write strTest
outFile.Close
End If
Output:
Here is the update of the code that works very well based on the response of #Gurman and the comment of #Ansgar Wiechers. Thank you for your help
Option Explicit
Dim File, objReg, strTest, RegExp, objMatches, objMatch, saveToFile, fso, outFile, strReplace, objShell, i
Set objShell = CreateObject("wscript.shell")
saveToFile = objShell.ExpandEnvironmentStrings("%windir%\Temp\test.txt")
Set File = CreateObject("MSXML2.XMLHTTP")
File.Open "GET","https://raw.githubusercontent.com/notracking/hosts-blocklists/master/domains.txt", False
File.send
If File.Status = 200 Then
'**********************************************************************************************
' Replace content for use with the file service.conf of soft Unbound_DNS
'
' address=/abc.com/0.0.0.0 to local-zone: "abc.com" redirect
' local-data: "abc.com 86400 IN A 0.0.0.0"
'**********************************************************************************************
strTest = File.responseText
Set RegExp = CreateObject("VBScript.RegExp")
RegExp.IgnoreCase = True
RegExp.Global = True
RegExp.Pattern = "address=/(.*?)/(\d{1,3}(?:\.\d{1,3}){3})"
strReplace = "local-zone: ""$1"" redirect" & vbCrLf & "local-data: ""$1 86400 IN A $2"""
strTest = RegExp.Replace(strTest, strReplace)
Set RegExp = Nothing
'**********************************************************************************************
' Write content
'**********************************************************************************************
Set fso = CreateObject("scripting.filesystemobject")
Set outFile = fso.OpenTextFile(saveToFile,2,True)
outFile.Write strTest
outFile.Close
End If

Vbscript Website Content, SelectAll Copy and Past into a Notepad *Help*

I got the code to copy the contents of a website into notepad:
With CreateObject("InternetExplorer.Application")
.Visible = False
.Navigate "https://example.com"
Do Until .ReadyState = 4
Wscript.Sleep 100
Loop
For Each Tag In .Document.GetElementsByTagName("script")
Tag.OuterHtml = ""
Next
For Each Tag In .Document.GetElementsByTagName("noscript")
Tag.OuterHtml = ""
Next
Content = .Document.GetElementsByTagName("body")(0).InnerText
Do While InStr(Content, vbCrLf & vbCrLf)
Content = Replace(Content, vbCrLf & vbCrLf, vbCrLf)
Loop
ShowInNotepad Content
.Quit
End With
Sub ShowInNotepad(Content)
With CreateObject("Scripting.FileSystemObject")
TempPath = CreateObject("WScript.Shell").ExpandEnvironmentStrings("%TEMP%") & "\" & .GetTempName
With .CreateTextFile(TempPath, True, True)
.WriteLine (Content)
.Close
End With
CreateObject("WScript.Shell").Run "notepad.exe " & TempPath, 1, True
.DeleteFile (TempPath)
End With
End Sub
I am stuck with above script to save the text as file.txt.
Please help.
Try something like that :
Option Explicit
Dim LogFile,Ws,Tag,Content
LogFile = Left(Wscript.ScriptFullName,InstrRev(Wscript.ScriptFullName, ".")) & "txt"
Set Ws = CreateObject("wscript.Shell")
With CreateObject("InternetExplorer.Application")
.Visible = False
.Navigate "https://example.com"
Do Until .ReadyState = 4
Wscript.Sleep 100
Loop
For Each Tag In .Document.GetElementsByTagName("script")
Tag.OuterHtml = ""
Next
For Each Tag In .Document.GetElementsByTagName("noscript")
Tag.OuterHtml = ""
Next
Content = .Document.GetElementsByTagName("body")(0).InnerText
Do While InStr(Content, vbCrLf & vbCrLf)
Content = Replace(Content, vbCrLf & vbCrLf, vbCrLf)
Loop
WriteLog Content,LogFile
.Quit
End With
Ws.Run LogFile
'*******************************************************************
Sub WriteLog(strText,LogFile)
Dim fso,ts
Const ForWriting = 2
Set fso = CreateObject("Scripting.FileSystemObject")
Set ts = fso.OpenTextFile(LogFile,ForWriting,True,-1)
ts.WriteLine strText
ts.Close
End Sub
'******************************************************************

VBS Downloader/updater not working

Credit to #Hackoo for the code below. I don't really know what's wrong with it, but it doesn't seem to wanna download the file (http://mollernielsen.eu/AutomaticShutdown/test.bat), which doesn't really make sense to me.
path = "http://mollernielsen.eu/AutomaticShutdown/test.bat"
pos = InStrRev(path, "/") +1
Const DownloadDest = "http://mollernielsen.eu/AutomaticShutdown/test.bat"
LocalFile = Mid(path, pos)
Const webUser = "admin"
Const webPass = "admin"
Const DownloadType = "binary"
dim strURL
function getit()
dim xmlhttp
set xmlhttp=createobject("MSXML2.XMLHTTP.3.0")
'xmlhttp.SetOption 2, 13056 'If https -) Ignorer toutes les erreurs SSL
strURL = DownloadDest
'Pour l'authentification de base, utilisez la liste ci-dessous, ainsi que les variables + d'utilisateurs? laisser passer
'xmlhttp.Open "GET", strURL, false, WebUser, WebPass
xmlhttp.Open "GET", strURL, false
xmlhttp.Send
If xmlhttp.Status = 200 Then
Dim objStream
set objStream = CreateObject("ADODB.Stream")
objStream.Type = 1 'adTypeBinary
objStream.Open
objStream.Write xmlhttp.responseBody
objStream.Close
set objStream = Nothing
End If
set xmlhttp=Nothing
End function
getit()
I have no clue what is wrong with the code, it seems to start, but no file is saved and there are no errors.
Try like this :
Option Explicit
Dim URL
URL = "http://mollernielsen.eu/AutomaticShutdown/test.bat"
Call DownloadingFile(URL)
'*************************************************************************************************
Sub DownloadingFile(URL)
On Error Resume Next
Dim objFSO,Ws,objXMLHTTP,PathScript,Tab,strHDLocation,objADOStream,File,ProtocoleHTTP
Set objFSO = Createobject("Scripting.FileSystemObject")
Set Ws = CreateObject("wscript.Shell")
PathScript = objFSO.GetParentFolderName(wscript.ScriptFullName) 'Path of this Vbscript
ProtocoleHTTP = "http://"
If URL = "" Then WScript.Quit
If Left(URL,7) <> ProtocoleHTTP Then
URL = ProtocoleHTTP & URL
End if
Tab = split(url,"/")
File = Tab(UBound(Tab))
File = Replace(File,"%20"," ")
File = Replace(File,"%28","(")
File = Replace(File,"%29",")")
Set objXMLHTTP = CreateObject("MSXML2.ServerXMLHTTP.3.0")
strHDLocation = PathScript & "\" & File
objXMLHTTP.open "GET",URL,false
objXMLHTTP.send()
If Err.number <> 0 or objXMLHTTP.Status <> 200 Then
MsgBox err.description & objXMLHTTP.Status,16,err.description & objXMLHTTP.Status
Exit Sub
Else
If objXMLHTTP.Status = 200 Then
strHDLocation = PathScript & "\" & File
Set objADOStream = CreateObject("ADODB.Stream")
objADOStream.Open
objADOStream.Type = 1 'adTypeBinary
objADOStream.Write objXMLHTTP.ResponseBody
objADOStream.Position = 0 'Set the stream position to the start
objADOStream.SaveToFile strHDLocation,2
objADOStream.Close
Set objADOStream = Nothing
End If
End if
Set objXMLHTTP = Nothing
ws.Popup "The Download of " & Dblquote(File) & " is finished ! ","5","The Download of " & Dblquote(File) & " is finished !" ,64
End Sub
'**********************************************************************************************
Function DblQuote(Str)
DblQuote = Chr(34) & Str & Chr(34)
End Function
'**********************************************************************************************
There's no actual SaveToFile method called in the script, but there should be. The stream is being saved to an object in memory, but never written to disk. Stick this above objStream.Close:
objStream.SaveToFile "test.bat", 2

Using VBS to Backup a file

I managed to find this script to use and backup my files, this is a little more complicated then I need it to be.
I do not need to enter a backup path - from and too every time I run it however this is a handy option for other projects but I would like to backup from a set file path and save to a set file path to save time.
The other issue with this script is the Cancel button does not work, this is an issue I have had before and fixed but I cannot remember how to make the Cancel button function.
Option Explicit
Dim objFSO, strSourceFolder, strDestFolder, strExclusion, strPrompt
Set objFSO = CreateObject("Scripting.FileSystemObject")
strSourceFolder = InputBox("Enter the Source directory path you wish to backup")
strDestFolder = InputBox("Enter the Destination directory path you wish to backup your Data to... (C:/Backup, //Backup-Server/Remotebackup")
Wscript.Echo "Click (OK) to start the Backup!"
CopyFolderStructure strSourceFolder, strDestFolder, strExclusion
Function CopyFolderStructure(strSource, strDestination, strExcludedExt)
Const OVER_WRITE_FILES = True
Dim objDir, objFolder, objFiles, strCurExt, intX, arrExt, blnExclude
Set objDir = objFSO.GetFolder(strSource)
If Not objFSO.FolderExists(strDestination & "\" & objDir.Name) Then
objFSO.CreateFolder(strDestination & "\" & objDir.Name)
End If
If Not IsNoData(strExcludedExt) Then
arrExt = Split(strExcludedExt, ",")
blnExclude = False
End If
For Each objFiles In objFSO.GetFolder(strSource).Files
If Not IsNoData(strExcludedExt) Then
strCurExt = objFSO.GetExtensionName(objFiles.Name)
For intX = 0 To UBound(arrExt)
If LCase(strCurExt) = arrExt(intX) Then
blnExclude = True
Exit For
Else
blnExclude = False
End If
Next
If Not blnExclude Then
objFSO.CopyFile strSource & "\" & objFiles.Name, strDestination & "\" & objDir.Name & "\" & objFiles.Name, OVER_WRITE_FILES
End If
Else
objFSO.CopyFile strSource & "\" & objFiles.Name, strDestination & "\" & objDir.Name & "\" & objFiles.Name, OVER_WRITE_FILES
End If
Next
For Each objFolder In objFSO.GetFolder(strSource).SubFolders
CopyFolderStructure objFolder.Path, strDestination & "\" & objDir.Name, strExcludedExt
Next
End Function
Function BrowseForFolderDialogBox(strTitle)
Const WINDOW_HANDLE = 0
Const NO_OPTIONS = &H0001
Dim objShellApp
Dim objFolder
Dim objFldrItem
Dim objPath
Set objShellApp = CreateObject("Shell.Application")
Set objFolder = objShellApp.BrowseForFolder(WINDOW_HANDLE, strTitle , NO_OPTIONS)
If IsNoData(objFolder) Then
WScript.Echo "You choose to cancel. This will stop this script."
Wscript.Quit
Else
Set objFldrItem = objFolder.Self
objPath = objFldrItem.Path
BrowseForFolderDialogBox = objPath
Set objShellApp = Nothing
Set objFolder = Nothing
Set objFldrItem = Nothing
End If
End Function
Function IsNoData(varVal2Check)
On Error Resume Next
If IsNull(varVal2Check) Or IsEmpty(varVal2Check) Then
IsNoData = True
Else
If IsDate(varVal2Check) Then
IsNoData = False
Elseif varVal2Check = "" Then
IsNoData = True
ElseIf Not IsObject(varVal2Check) Then
IsNoData = False
Else
IsNoData = False
End If
End If
End Function
Wscript.Echo "Backup Has Completed Successfully"
Next code snippet could help (see Arguments Property (WScript Object), InputBox Function and MsgBox Function reference). Note that the Echo method behaves differently depending on which WSH engine you are using.
Option Explicit
Dim objFSO, strSourceFolder, strDestFolder, strExclusion, strPrompt
Dim iBut, sRes, sMes, objArgs
sRes = Wscript.ScriptName
sMes = vbCRLF & "(click (Cancel) button to discard)"
Set objArgs = WScript.Arguments
If objArgs.Count > 1 Then
strSourceFolder = objArgs( 0)
strDestFolder = objArgs( 1)
Else
strSourceFolder = "C:/DataToBackup"
strDestFolder = "D:/Backup"
strSourceFolder = InputBox( "Path you wish to backup" & sMes _
, "Source directory", strSourceFolder)
sRes = sRes & vbNewLine & "strSourceFolder """ & strSourceFolder & """"
If strSourceFolder = "" Then
strDestFolder = ""
Else
strDestFolder = InputBox( "Path you wish to backup your Data to" & sMes _
, "Destination directory", strDestFolder)
sRes = sRes & vbNewLine & "strDestFolder """ & strDestFolder & """"
End If
End If
If strDestFolder = "" Then
sRes = sRes & vbNewLine & "Backup Cancelled!"
Wscript.Echo sRes
Wscript.Quit
Else
iBut=MsgBox(sRes & sMes, vbOKCancel + vbQuestion _
, "Click (OK) to start the Backup!")
If iBut <> vbOK Then Wscript.Quit
End If
'''' for debugging only:
Wscript.Quit '''' for debugging only:
'''' for debugging only:
Set objFSO = CreateObject("Scripting.FileSystemObject")
CopyFolderStructure strSourceFolder, strDestFolder, strExclusion
'''''' and so on...

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