VBScript on Windows to download file from SharePoint [duplicate] - vbscript

This question already has answers here:
Unrecognized database format'C:\.....\Employees.accdb for Microsoft Access Database File?
(2 answers)
Running VBS script from VBA - Unrecognized DB Format
(1 answer)
Closed 14 days ago.
This post was edited and submitted for review 13 days ago.
Is it possible to execute a VB Script (.vbs) from a Windows desktop to download a file from a SharePoint URL to a local folder and then open the file.
I'm using this with Access databases and below is the code I currently have. This seems to work but when it tries to open the file I get the "unrecognized database format error".
I've used a similar script to do this off the NAS and it works file, it's just an issue now that these files are getting moved to SharePoint.
Dim objShell, objEnv, objFSO, objFile, objFSO2, strDir, ServerDBFile, LocalDBFile
SET objShell = CreateObject("wscript.Shell")
SET objEnv = objShell.Environment("Process")
SET objFSO = CreateObject("Scripting.FileSystemObject")
SET objFSO2 = CreateObject("Scripting.FileSystemObject")
LocalDBFile = objEnv("USERPROFILE") & "\Documents\Database\DSEP\TESTING\DSEP_FE_SQL.accdb"
'ServerDBFile = "\\nas.rchsd.org\depts\DSEP\database\Staging\SQL Server\DSEP_SQL\Dev\DSEP_FE_SQL.accdb"
ServerDBFile = "https://rchsdorg.sharepoint.com/sites/RCHSD-DSEP-Test-DevlplScrngEnhancmntPrgm-M365/Shared%20Documents/General/DSEP%20Staging/DSEP/DSEP_FE_SQL.accdb?csf=1&web=1&e=FtLS9U"
'SET objFile = objFSO.GetFile(ServerDBFile)
'Create an HTTP object
SET objHTTP = CreateObject("WinHttp.WinHttpRequest.5.1" )
dim bStrm: SET bStrm = CreateObject("Adodb.Stream")
'Download the specified URL
objHTTP.Open "GET", ServerDBFile, False
objHTTP.Send ""
'Check for Database folders
strDir = objEnv("USERPROFILE") & "\Documents\Database"
If objFSO.FolderExists(strDir) Then
'wscript.echo "Database Path Exists"
Else
'wscript.echo "Creating Network location"
objFSO.CreateFolder(strDir)
End If
'Check for DSEP folder
strDir = objEnv("USERPROFILE") & "\Documents\Database\DSEP"
If objFSO.FolderExists(strDir) Then
'wscript.echo "Database\DSEP Path Exists"
Else
'wscript.echo "Creating Network location"
objFSO.CreateFolder(strDir)
End If
'Check for TESTING folder
strDir = objEnv("USERPROFILE") & "\Documents\Database\DSEP\TESTING"
If objFSO.FolderExists(strDir) Then
'wscript.echo "Database\DSEP\TESTING Path Exists"
Else
'wscript.echo "Creating Network location"
objFSO.CreateFolder(strDir)
End If
'Delete local file if found.
If (objFSO.FileExists(LocalDBFile)) Then
'wscript.echo "Local File Exists"
objFSO.DeleteFile(LocalDBFile)
'wscript.echo "Local File Deleted"
End If
If objHTTP.Status = 200 Then 'Expecting a HTTP 200 OK response
With bStrm
.Type = adTypeBinary '//binary
.Open
.Write objHTTP.responseBody
.SaveToFile LocalDBFile, 2 '//overwrite
End With
Else
'Check the response body for details of the error.
wscript.echo "Unexpected response: " & objHTTP.Status & " - " & objHTTP.StatusText, 48, "Error"
End If
set accessApp = createObject("Access.Application")
accessApp.visible = true
accessApp.UserControl = true
accessApp.OpenCurrentDataBase(LocalDBFile)

Related

How to download files using VBScript? [duplicate]

This question already has answers here:
Download a file with VBS
(6 answers)
Closed last year.
I've been trying to download a dancing banana Png lately (just to learn how) and have just not been having any luck. Whenever I try something out it gives me an error that says Write to File failed and gives me 800A0BBC as the code. What am I doing wrong? Thanks in advance!
Code:
dim xHttp: Set xHttp = createobject("Microsoft.XMLHTTP")
dim bStrm: Set bStrm = createobject("Adodb.Stream")
xHttp.Open "GET", "https://wallpapercave.com/wp/wp5042624.png", False
xHttp.Send
with bStrm
.type = 1 '//binary
.open
.write xHttp.responseBody
.savetofile "c:\temp\wp5042624.png", 2 '//overwrite
end with
I don't know if you have in your code that you tried before an extra quote or your code is not well formatted; anyway , give a try for this code that save your image in a folder named Images_PNG created on your desktop just for testing !
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set Ws = CreateObject("WScript.Shell")
strDirectory = "Images_PNG"
strDirectory = objFSO.BuildPath(Ws.SpecialFolders("Desktop"), strDirectory)
If not objFSO.FolderExists(strDirectory) Then objFSO.CreateFolder(strDirectory)
URL = "https://wallpapercave.com/wp/wp5042624.png"
Save2File = strDirectory & "\wp5042624.png"
Call Download(URL,Save2File)
MsgBox "Terminted !",vbInformation,"Download PNG File"
'--------------------------------------------------------------------------------------------
Sub Download(URL,Save2File)
Dim File,Line,BS,ws
On Error Resume Next
Set File = CreateObject("Microsoft.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 ' File exists and it is ready to be downloaded
Set BS = CreateObject("ADODB.Stream")
Set ws = CreateObject("wscript.Shell")
BS.type = 1
BS.open
BS.Write File.ResponseBody
BS.SaveToFile Save2File, 2
ElseIf File.Status = 404 Then
MsgBox "File Not found : " & File.Status,vbCritical,"Error File Not Found"
Else
MsgBox "Unknown Error : " & File.Status,vbCritical,"Error getting file"
End If
End Sub
'-------------------------------------------------------------------------

How do I add to a to VBS file command

I have the following VBScript to which I'm trying to add to, but I need help in how to do it.
At present I have the script below that asks for the file name I want it to be called and then creates a folder and moves of which ok.
What I'm trying to add is after the folder is created I need a command box with the YES/NO option and if I click YES I need the file moved to C:\DOCUMENTS\A and if NO I need it moved to C:\DOCUMENTS\B.
Once I've clicked YES or NO and it has moved the folder I need to open Folder A or B to view.
Any Ideas?
Option Explicit
Const strDLFolder = "C:\Downloads"
Dim objFSO, objWShell, objDLFolder, strNewFolder, objFile
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objWShell = CreateObject("WScript.Shell")
If Not objFSO.FolderExists(strDLFolder) Then objFSO.CreateFolder(strDLFolder)
objWShell.CurrentDirectory = strDLFolder
Set objDLFolder = objFSO.GetFolder(strDLFolder)
If objDLFolder.Files.Count = 0 Then WScript.Quit
Do
Err.Clear
strNewFolder = InputBox("Folder Name", vbLf & "Enter the name of the folder to be created:")
If strNewFolder = False Then WScript.Quit
On Error Resume Next
objFSO.CreateFolder strNewFolder
Loop While Err.Number <> 0 Or Not objFSO.FolderExists(strNewFolder)
On Error Goto 0
For Each objFile In objDLFolder.Files
objFSO.MoveFile objFile.Name, strNewFolder & "\"
Next
objWShell.Popup "All files moved.", 0, "Done", vbInformation Or vbSystemModal Or &h00040000&

Error with vbscript to download a file bypassing invalid certificate errors

having a similar problem to this post:
Previous older post here
I'm trying to download a file from a webserver that works great on my internal and external network but not when i try to download from a secure https:// server.
I get the following error Error picture here
I Have tried copying info from above problem but i'm not getting it right. can you please assist?
It works great internally and externally if not trying to access https!
Dim strURL, strFile, strFolder, oFSO, dt, oHTTP, oStream
strURL = "https://xx.xx.xx.xx/DataLogs/xxx.csv" 'external secure site
'strURL = "http://192.168.1.10/DataLogs/PLCData.csv" 'internal test
FileName="xxx.csv"
'FileName="PLCData.csv"
strFile = "xxx.csv" ''# The file name
'strFile = "PLCData.csv" ''# The file name
strFolder = "C:\PLC Data" '# The folder where to save the files
Const adTypeBinary = 1
Const adSaveCreateOverWrite = 2
''# If the download folder doesn't exist, create it
Set oFSO = CreateObject("Scripting.FileSystemObject")
If Not oFSO.FolderExists(strFolder) Then
oFSO.CreateFolder strFolder
End If
Set dt = CreateObject("WbemScripting.SWbemDateTime")
dt.SetVarDate Now
strFile = oFSO.GetBaseName(strFile) & "-" & Split(dt.Value, ".")(0) & "." & oFSO.GetExtensionName(strFile)
''# Download the URL
Set oHTTP = CreateObject("MSXML2.ServerXMLHTTP") 'replace with? Set oHTTP = CreateObject("MSXML2.XMLHTTP") MSXML2.ServerXMLHTTP
oHTTP.open "GET", strURL, False
oHTTP.send
If oHTTP.Status <> 200 Then
''# Failed to download the file
WScript.Echo "Error " & oHTTP.Status & ": " & oHTTP.StatusText
Else
Set oStream = CreateObject("ADODB.Stream")
oStream.Type = adTypeBinary
oStream.Open
''# Write the downloaded byte stream to the target file
oStream.Write oHTTP.ResponseBody
oStream.SaveToFile oFSO.BuildPath(strFolder, strFile), adSaveCreateOverWrite
oStream.Close
End If

How to run command to set credentials from within vbs script using system account?

Salvete!
On my server I am running hMailServer, and that service uses the local system account.
I need to copy a file to another machine. So I have this a script that will use cmdkey.exe to save the credentials and then copy the file.
If I run this function myself (in a standalone vbs file) whilst logged into the server, it works, but I am admin.
However, if I let the hMailServer service run this function, the function runs, but it always says the destination does not exist.
Notice I have commented out the deletion of the credentials. If I go to the server and run cmdkey /list I see that the credentials were never set, which means the command failed. That means the first setting of the credentials probably failed too, which is why 'objFSO' cannot find the directory.
Again, if I put all this in a separate file and run it as test.vbs by double-clicking the file, it works. But if I use it from within hMailServer, it fails.
I suppose this means the hMailServer (local system account) doesn't have rights to set credentials? How do I get this to work?
option explicit
dim SPcopyMessage
SPcopyMessage = CopyFileToRemoteMachine("SERVER", "mydomain\username", "password", "c:\test2.txt", "\\SERVER\somefolder\otherfolder")
MsgBox SPcopyMessage
function CopyFileToRemoteMachine(whatMachine, whatUsername, whatPassword, whatSourceFile, whatDestination)
dim errormessage, CredentialCreate, CredentialDelete
errormessage = "Sharepoint Mail Delivered"
CredentialCreate = "cmd.exe /c cmdkey /add:" & whatMachine & " /user:" & whatUsername & " /pass:" & whatPassword
Dim objShell, objFSO
Set objShell = CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
CALL objShell.Run(CredentialCreate, 0, True) 'add username to the credentials list
If objFSO.FileExists(whatSourceFile) Then
If objFSO.FolderExists(whatDestination) Then
If Right(whatDestination, 1) <> "\" Then
whatDestination = whatDestination & "\"
End If
objFSO.CopyFile whatSourceFile, whatDestination, True
Else
errormessage = "Destination does not exist: " & whatDestination
End If
Else
errormessage = "Source file does not exist: " & whatSourceFile
End If
'CredentialDelete = "cmd.exe /c cmdkey /delete:" & whatMachine
'CALL objShell.Run(CredentialDelete, 0, True)
set objFSO = nothing
set objShell = nothing
CopyFileToRemoteMachine = errormessage
end function
Figured out a way! First, I made sure the destination was shared to the right user account on machine2. Then made the script on machine1 to map the network drive and then copy the file. This will work as long as the N drive is never used for anything else on that machine.
Here is the code is if be helpful to anyone!
function CopyFileToRemoteMachine(whatMachine, whatUsername, whatPassword, whatSourceFile, whatDestination)
dim errormessage, mdrive
errormessage = "File successfully copied"
mdrive = "N:"
Dim objFSO, objNetwork
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objNetwork = CreateObject("Wscript.Network")
If not objFSO.FileExists(mdrive) Then
objNetwork.MapNetworkDrive mdrive, whatDestination, False, whatUsername, whatPassword
End If
If Right(whatDestination, 1) <> "\" Then
whatDestination = whatDestination & "\"
End If
If objFSO.FileExists(whatSourceFile) Then
If objFSO.FolderExists(whatDestination) Then
objFSO.CopyFile whatSourceFile, whatDestination, True
Else
errormessage = "Destination does not exist: " & whatDestination
End If
Else
errormessage = "Source file does not exist: " & whatSourceFile
End If
objNetwork.RemoveNetworkDrive mdrive,TRUE,TRUE
set objFSO = nothing
set objNetwork = nothing
CopyFileToRemoteMachine = errormessage
end function

Programmatically add 'My Network Place' for FTP site?

Is there anyway I can create a small exe or batch file to setup a new 'My Network Place' in Windows? Its for an ftp site if that makes any difference.
XP will primarily be the target machine but If I can find something that will work on Vista too thats great.
I wrote this script to connect to a FTP using a proxy server. You could adapt it for your needs. It prompts for the filename and folder you are trying to access. Just cut the code you don't need, and you should be good to go.
You will need to change the FTP Server Name variable as well. Happy coding:
Option Explicit
Dim objShell, strFTPScriptFileName, strFile2Get
Dim strLocalFolderName, strFTPServerName, strLoginID
Dim strPassword, strFTPServerFolder, strFileToGet, returnCode
'Customize code here to fit your needs
strFTPServerName = "proxy.prv"
strLocalFolderName = ""
strLoginID = ""
strPassword = ""
strFTPServerFolder = ""
strFileToGet = ""
strLocalFolderName = GetLocalFolder()
strLoginID = InputBox("Enter FTP Username: ", "Enter FTP Username", "Authentication_Method#Destination_FTP_Host")
strPassword = InputBox("Enter FTP Password: ", "Enter FTP Password", "Authentication_Method#Destination_FTP_Host")
strFTPServerFolder = InputBox("Enter FTP folder that you want to access: ", "Enter FTP Folder", "/")
strFileToGet = InputBox("Enter the filename located on the FTP that you want to retrieve: ", "Enter FTP file", "*.*")
if strLoginID = "" then
WScript.Echo "You must specify a Login ID for this script to work"
WScript.Quit()
end if
if strPassword = "" then
WScript.Echo "You must specify a Password for this script to work"
WScript.Quit()
end if
if strFTPServerFolder = "" then
WScript.Echo "You must specify a FTP Folder to access for this script to work"
WScript.Quit()
end if
if strFileToGet = "" then
WScript.Echo "You must specify a Filename to download for this script to work"
WScript.Quit()
end if
Call WriteFTPScript()
Set objShell = WScript.CreateObject( "WScript.Shell" )
returnCode = objShell.Run( "cmd.exe /c ftp -s:" & chr(34) & strFTPScriptFileName & chr(34), 1, true)
if (returnCode = 0) then
Wscript.echo("Your file has been downloaded.")
else
Wscript.echo("An error has occured while attempting to download your file.")
End if
objShell.Run (strLocalFolderName)
Set objShell = Nothing
' **************************************************************************
' Creates the FTP script text file
Function WriteFTPScript()
Dim objFSO, objMyFile
strFTPScriptFileName = strLocalFolderName & "\FTPScript.txt" 'File to be created to hold ftp script data
Set objFSO = CreateObject("Scripting.FileSystemObject")
If (objFSO.FileExists(strFTPScriptFileName)) Then
objFSO.DeleteFile (strFTPScriptFileName)
End If
Set objMyFile = objFSO.CreateTextFile(strFTPScriptFileName, True)
objMyFile.WriteLine ("open " & strFTPServerName)
objMyFile.WriteLine (strLoginID)
objMyFile.WriteLine (strPassword)
objMyFile.WriteLine ("cd " & strFTPServerFolder)
objMyFile.WriteLine ("lcd " & strLocalFolderName)
objMyFile.WriteLine ("get " & strFileToGet)
objMyFile.WriteLine ("bye")
objMyFile.Close
Set objFSO = Nothing
Set objMyFile = Nothing
End Function
' **************************************************************************
' Dialog box to select folder to download to
Function GetLocalFolder()
Const BIF_returnonlyfsdirs = &H0001
Const BIF_editbox = &H0010
Dim wsh, objDlg, objF
Set objDlg = WScript.CreateObject("Shell.Application")
Set objF = objDlg.BrowseForFolder (&H0, "Select the destination folder to download FTP files to:", BIF_editbox + BIF_returnonlyfsdirs)
If IsValue(objF) Then
GetLocalFolder = objF.ParentFolder.ParseName(objF.Title).Path
Else
WScript.Echo "You MUST specify a folder to download files to. Application will now exit."
WScript.Quit
End If
end function
' **************************************************************************
' Verifies if the the object contains a value
Function IsValue(obj)
Dim tmp
On Error Resume Next
tmp = " " & obj
If Err <> 0 Then
IsValue = False
Else
IsValue = True
End If
On Error GoTo 0
End Function
' **************************************************************************
' Verifies if the the object is a folder
Function IsFolder(obj)
Dim objFSO
Set objFSO = CreateObject("Scripting.FileSystemObject")
if objFSO.IsFolder(obj) then
IsFolder = True
end if
End Function
Yes, there is. The NetHood folder can be manipulated with vbScript. Refer to this forum thread for more information. The following works for me on XP Pro:
Option Explicit
On Error Goto 0
'ShellSpecialFolderConstants
Const ssfNETHOOD = 19 '(&H13) Special Folder NETHOOD
Dim objWSHShell, objShell, objFolder, objFolderItem, strNetHood
Dim strShortcutName, strShortcutPath, objShortcut
Set objWSHShell = CreateObject("Wscript.Shell")
Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.Namespace(ssfNETHOOD)
Set objFolderItem = objFolder.Self
strNetHood = objFolderItem.Path
strShortcutName = "FTP to localhost"
strShortcutPath = "ftp://username#localhost/"
Set objShortcut = objWSHShell.CreateShortcut(strNetHood & "\" & strShortcutName & ".lnk")
objShortcut.TargetPath = strShortcutPath
objShortcut.Save

Resources