VBS Downloader/updater not working - vbscript

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

Related

Error while uploading file in web server in every 10 sec

The following code i used for Uploading code without loop and code works fine while i use no loop function.
dim strURL
Dim password
Dim username
Set wshShell = CreateObject("WScript.Shell")
UploadDest= wshShell.ExpandEnvironmentStrings("https://webdav.pcloud.com/Public%20Folder/")
UploadFile = wshShell.ExpandEnvironmentStrings("%username%.txt")
username = "abc#gmail.com"
password = "abc"
sData = getFileBytes(UploadFile, UploadType)
Set HttpReq =createobject("Microsoft.XMLHTTP")
strURL = UploadDest & "/" & UploadFile
HttpReq.Open "PUT",strURL,False,username,password
HttpReq.send sData
function getFileBytes(flnm,sType)
Dim objStream
Set objStream = CreateObject("ADODB.Stream")
if sType="binary" then
objStream.Type = 1 ' adTypeBinary
else
objStream.Type = 2 ' adTypeText
objStream.Charset ="ascii"
end if
objStream.Open
objStream.LoadFromFile flnm
if sType="binary" then
getFileBytes=objStream.Read 'read binary'
else
getFileBytes= objStream.ReadText 'read ascii'
end if
objStream.Close
Set objStream = Nothing
end function
But when I use above code in loop i got syntax error in line no:12
function getFileBytes(flnm,sType)
I used following code to upload file in loop in every 10 sec .
set i = 0
Do While i = 0
dim strURL
Dim password
Dim username
Set wshShell = CreateObject("WScript.Shell")
UploadDest= wshShell.ExpandEnvironmentStrings("https://webdav.pcloud.com/Public%20Folder/")
UploadFile = wshShell.ExpandEnvironmentStrings("%username%.txt")
username = "abc#gmail.com"
password = "abc"
sData = getFileBytes(UploadFile, UploadType)
Set HttpReq =createobject("Microsoft.XMLHTTP")
strURL = UploadDest & "/" & UploadFile
HttpReq.Open "PUT",strURL,False,username,password
HttpReq.send sData
function getFileBytes(flnm,sType)
Dim objStream
Set objStream = CreateObject("ADODB.Stream")
if sType="binary" then
objStream.Type = 1 ' adTypeBinary
else
objStream.Type = 2 ' adTypeText
objStream.Charset ="ascii"
end if
objStream.Open
objStream.LoadFromFile flnm
if sType="binary" then
getFileBytes=objStream.Read 'read binary'
else
getFileBytes= objStream.ReadText 'read ascii'
end if
objStream.Close
Set objStream = Nothing
end function
WScript.Sleep(10000)
loop
You can't define a Function inside a Loop
Rewrite like this to define the function outside of the loop:
Dim i
Do While i = 0
dim strURL
Dim password
Dim username
Set wshShell = CreateObject("WScript.Shell")
UploadDest= wshShell.ExpandEnvironmentStrings("https://webdav.pcloud.com/Public%20Folder/")
UploadFile = wshShell.ExpandEnvironmentStrings("%username%.txt")
username = "abc#gmail.com"
password = "abc"
sData = getFileBytes(UploadFile, UploadType)
Set HttpReq =createobject("Microsoft.XMLHTTP")
strURL = UploadDest & "/" & UploadFile
HttpReq.Open "PUT",strURL,False,username,password
HttpReq.send sData
WScript.Sleep(10000)
loop
function getFileBytes(flnm,sType)
Dim objStream
Set objStream = CreateObject("ADODB.Stream")
if sType="binary" then
objStream.Type = 1 ' adTypeBinary
else
objStream.Type = 2 ' adTypeText
objStream.Charset ="ascii"
end if
objStream.Open
objStream.LoadFromFile flnm
if sType="binary" then
getFileBytes=objStream.Read 'read binary'
else
getFileBytes= objStream.ReadText 'read ascii'
end if
objStream.Close
Set objStream = Nothing
end function

Download file via vbs

I know this has been asked and answered, it is where I found the code to start my project. But it doesn't work.
I'm stuck. I have tried and tried and the code(s) don't work.
Dim xHttp: Set xHttp = CreateObject("Microsoft.XMLHTTP")
Dim bStrm: Set bStrm = CreateObject("Adodb.Stream")
xHttp.Open "GET", "https://filexxx.exe", False
xHttp.Send
With bStrm
.Type = 1 'binary
.Open
.Write xHttp.ResponseBody 'this part removed, error, tools not yet avail
.SaveToFile "c:\temp\xxx.exe", 2 'overwrite
End With
And this one.
strFileURL = "https://filexxx.exe"
strHDLocation = "C:\temp\xxx.exe"
Set objXMLHTTP = CreateObject("MSXML2.ServerXMLHTTP.6.0")
objXMLHTTP.Open "GET", strFileURL, False
objXMLHTTP.Send()
Set objADOStream = CreateObject("ADODB.Stream")
objADOStream.Open
objADOStream.Type = 1 'adTypeBinary
objADOStream.SaveToFile strHDLocation
And this one.
strFileURL = "https://filexxx.exe"
strHDLocation = "C:\temp\filexxx.exe"
proxy = null
Set objXMLHTTP = CreateObject("MSXML2.ServerXMLHTTP")
Set wshShell = CreateObject( "WScript.Shell" )
Set objUserVariables = wshShell.Environment("USER")
'http proxy is optional
'attempt to read from HTTP_PROXY env var first
On Error Resume Next
If Not (objUserVariables("HTTP_PROXY") = "") Then
proxy = objUserVariables("HTTP_PROXY")
ElseIf Not (WScript.Arguments.Named("proxy") = "") Then
proxy = WScript.Arguments.Named("proxy")
End If
If Not isNull(proxy) Then
Set objXMLHTTP = CreateObject("MSXML2.ServerXMLHTTP.6.0")
objXMLHTTP.SetProxy 2, proxy
End If
On Error Goto 0
objXMLHTTP.Open "GET", strFileURL, False
objXMLHTTP.Send()
Set objADOStream = CreateObject("ADODB.Stream")
objADOStream.Open
objADOStream.Type = 1
objADOStream.Position = 0
Set objFSO = Createobject("Scripting.FileSystemObject")
If objFSO.Fileexists(path) Then objFSO.DeleteFile path
Set objFSO = Nothing
objADOStream.SaveToFile strHDLocation
objADOStream.Close
Set objADOStream = Nothing
Set objXMLHTTP = Nothing
And this one
HTTPDownload "https:filexxx.exe", "C:\temp\filexxx.exe"
Sub HTTPDownload(myURL, myPath)
' Standard housekeeping
Dim i, objFile, objFSO, objHTTP, strFile, strMsg
Const ForReading = 1, ForWriting = 2, ForAppending = 8
' Create a File System Object
Set objFSO = CreateObject("Scripting.FileSystemObject")
' Check if the specified target file or folder exists,
' and build the fully qualified path of the target file
If objFSO.FolderExists(myPath) Then
strFile = objFSO.BuildPath(myPath, Mid(myURL, InStrRev(myURL, "/") + 1))
ElseIf objFSO.FolderExists(Left(myPath, InStrRev(myPath, "\") - 1)) Then
strFile = myPath
Else
WScript.Echo "ERROR: Target folder not found."
Exit Sub
End If
' Create or open the target file
Set objFile = objFSO.OpenTextFile(strFile, ForWriting, True)
' Create an HTTP object
Set objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
' Download the specified URL
objHTTP.Open "GET", myURL, False
objHTTP.Send
' Write the downloaded byte stream to the target file
For i = 1 To LenB(objHTTP.ResponseBody)
objFile.Write Chr(AscB(MidB(objHTTP.ResponseBody, i, 1)))
Next
' Close the target file
objFile.Close()
End Sub
All have same result. They don't download the file. Sometimes one of them freezes the computer and I have to manually power down.
They do, after time, download (but don't) and only shows file as 0kb. If I change
objXMLHTTP.Open "GET", strFileURL, False
to
objXMLHTTP.Open "GET", strFileURL, True
It instantly shows up in folder and shows 0kb
Either True or False, waiting 30+ minutes does nothing to size of file. The actual file size is 1,874,886 kB and only takes a couple minutes to download from website.
Dim ie
Set ie = CreateObject("InternetExplorer.Application")
ie.Visible = False
ie.Navigate2("https://filexxx.exe")
ie.Document.Execwb("saveas", False, "C:\temp\filexxxx.exe")
ie.Quit
Gives
line 5 char 58 cannot use parentheses when calling a sub
And if I remove the quotation marks "" from drive\folder\file I get
line 5 char 36 expected ")"
Note the URL is https, not http. Been working on this for couple days now.
I don't know what the point of posting random code is. The point of this code is it says what is happening.
Set fso = CreateObject("Scripting.FileSystemObject")
Set Outp = Wscript.Stdout
Set wshShell = CreateObject("Wscript.Shell")
Set ShApp = CreateObject("Shell.Application")
On Error Resume Next
Set File = WScript.CreateObject("Msxml2.XMLHTTP.6.0")
File.Open "GET", "https://www.google.com.au/search?q=cat"), False
File.setRequestHeader "User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0; SLCC1; .NET CLR 2.0.50727; Media Center PC 5.0; .NET CLR 1.1.4322; .NET CLR 3.5.30729; .NET CLR 3.0.30618; .NET4.0C; .NET4.0E; BCD2000; BCD2000)"
File.Send
wscript.echo ""
wscript.echo "Error getting file"
wscript.echo "=================="
wscript.echo ""
wscript.echo "Error " & err.number & "(0x" & hex(err.number) & ") " & err.description
wscript.echo "Source " & err.source
wscript.echo ""
wscript.echo "HTTP Error " & File.Status & " " & File.StatusText
wscript.echo File.getAllResponseHeaders
wscript.echo File.ResponseBody
On Error Goto 0
wscript.echo "Server Response " & File.Status & " " & File.StatusText
wscript.echo File.getAllResponseHeaders
Set BS = CreateObject("ADODB.Stream")
BS.type =1
' BS.Charset = "utf-8"
BS.open
BS.Write File.ResponseBody
BS.Position = 0
BS.type =2
BS.Charset = "utf-8"
wscript.echo BS.ReadText
Set BS = CreateObject("ADODB.Stream")
BS.type = 1
BS.open
BS.Write File.ResponseBody
BS.SaveToFile ShApp.Namespace(&h10).self.path & "\Google.html]", 2
' wshshell.Run "c:\users\safetyscanner.exe", 1, False

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
'******************************************************************

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...

VBS to open multiple URL from a list and save to file

I have multiple webpages that I need to open and save the information, which is just text, to a new file for each one. I am not that experienced in VBScripts, at all. But, I have been searching for days and here is what I have gathered so far:
function download(sFileURL, sLocation, async)
set objXMLHTTP = CreateObject("MSXML2.XMLHTTP")
objXMLHTTP.open "GET", sFileURL, async
on error resume next
objXMLHTTP.send()
if err.number = 0 then
do until objXMLHTTP.Status = 200
wscript.echo objXMLHTTP.Status
wcript.sleep(200)
loop
if objXMLHTTP.Status = 200 Then
set objADOStream = CreateObject("ADODB.Stream")
objADOStream.Open
objADOStream.Type = 1
objADOStream.Write objXMLHTTP.ResponseBody
objADOStream.Position = 0
set objFSO = Createobject("Scripting.FileSystemObject")
If objFSO.Fileexists(sLocation) Then objFSO.DeleteFile sLocation
Set objFSO = Nothing
objADOStream.SaveToFile sLocation
objADOStream.Close
set objADOStream = Nothing
download = true
end if
else
download = false
end if
set objXMLHTTP = Nothing
end function
if download("http://books.google.com/books/feeds/volumes?q=isbn", "test.txt", false) then
wscript.echo "download ok"
else
wscript.echo "download did not work"
end if
How can I change the
if download("http://books.google.com/books/feeds/volumes?q=isbn", "test.txt", false)
to read from a list in text file, and save as test00, test01, test02,...
Thank you in advance
This is the simplest code that should do what you need.
Set objFSO = CreateObject("Scripting.FileSystemObject")
ListFile = "D:\list.txt"
Set objFile = objFSO.OpenTextFile(ListFile)
FileNumber = 0
Do Until objFile.AtEndOfStream
URLFromList = objFile.ReadLine
FileNumber = FileNumber + 1
if download(URLFromList, "test" & FileNumber & ".txt", false) then
wscript.echo "download ok for " & URLFromList
else
wscript.echo "download did not work for " & URLFromList
end if
Loop
objFile.Close
objFSO = Nothing

Resources