vbs script to send files via ftp and check/delete

2019-05-29 02:05发布

问题:

I'm trying to send files over ftp and afterwards check if the process was completed successfully, if it was I would delete the original files and keep only the ones sent in the destination folder on FTP.

I managed to patch up a script that connects to FTP and sends the files, but I'm not sure how to cross check original folder with the one on the FTP so I could determine if the copy was successful.

This is the code to send files over FTP, and in testing it sends successfully all the files, but I have to check before deletion

Set oShell = CreateObject("Shell.Application")
Set objFSO = CreateObject("Scripting.FileSystemObject")

path = "D:\test\"

FTPUpload(path)
Sub FTPUpload(path)

On Error Resume Next

Const copyType = 16

'FTP Wait Time in ms
waitTime = 80000

FTPUser = "test"
FTPPass = "testtest"
FTPHost = "ftp.test.com"
FTPDir = "/htdocs/test/"

strFTP = "ftp://" & FTPUser & ":" & FTPPass & "@" & FTPHost & FTPDir
Set objFTP = oShell.NameSpace(strFTP)


'Upload single file       
If objFSO.FileExists(path) Then

Set objFile = objFSO.getFile(path)
strParent = objFile.ParentFolder
Set objFolder = oShell.NameSpace(strParent)

Set objItem = objFolder.ParseName(objFile.Name)

Wscript.Echo "Uploading file " & objItem.Name & " to " & strFTP
 objFTP.CopyHere objItem, copyType


End If


'Upload all files in folder
If objFSO.FolderExists(path) Then

'Entire folder
Set objFolder = oShell.NameSpace(path)

Wscript.Echo "Uploading folder " & path & " to " & strFTP
objFTP.CopyHere objFolder.Items, copyType

End If


If Err.Number <> 0 Then
Wscript.Echo "Error: " & Err.Description
End If

'Wait for upload
Wscript.Sleep waitTime

End Sub

I would appreciate any kind of help, thank you.

回答1:

Not sure if this is the best way but you can get a file listing via the FTP command and compare the results to what you're expecting. Here's an example:

' Create the FTP command file...
With CreateObject("Scripting.FileSystemObject").CreateTextFile("c:\ftp.txt", True)
    .WriteLine "USER test"
    .WriteLine "testtest"
    .WriteLine "ls /htdocs/test/"
    .WriteLine "quit"
    .Close
End With

' Run the command and capture its output...
With CreateObject("WScript.Shell")
    .Run "%comspec% /c ftp -n -v -s:c:\ftp.txt ftp.test.com >c:\filelist.txt", 0, True
End With

This would create the file c:\filelist.txt, which you could then open and check for the existence of the file(s) you've uploaded. Of course, you can add additional args to the ls command to get more detailed info. For example, ls -l would give you the date updated as well as the file size.



标签: vbscript ftp