2012-02-17 2 views
1

Я настолько смущен этим, я пытаюсь загрузить данные на FTP через скрипт VBS, и он отлично работает для одного файла, но не загружает несколько файлов, когда я добавляю скрипт внутри цикла.Зачем нам создавать временный файл при удаленной загрузке на FTP?

Кроме того, почему мы должны сгенерировать временный файл при удаленном загрузки на FTP,

Я хочу сказать это,

это скрипт я использую,

Dim fso, folder, files, strPath 
Set fso = CreateObject("Scripting.FileSystemObject") 

strPath = "E:/Test" 
Set folder = fso.GetFolder(strPath) 
Set files = folder.Files 

Const hostname = "ftp.domain.com" 
Const port = 21 
Const username = "username" 
Const password = "password" 
Const remoteDir = "/" 
Const useDefaultsExclusively = True 
Const skipConfirmation = True 


For each item In files 

    If InStr(1, item.Name, "txt") <> 0 Then 
    defaultFile = item.Name 
    localFile = fso.getFileName(defaultFile) 
    localDir = fso.getParentFolderName(defaultFile) 
    Set shell = CreateObject("WScript.Shell") 

    tempDir = shell.ExpandEnvironmentStrings("%TEMP%") 
    ' temporary script file supplied to Windows FTP client 
    scriptFile = tempDir & "\" & fso.GetTempName 
    ' temporary file to store standard output from Windows FTP client 
    outputFile = tempDir & "\" & fso.GetTempName 

    'input script 
    script = script & "lcd " & """" & localDir & """" & vbCRLF 
    script = script & "open " & hostname & " " & port & vbCRLF 
    script = script & "user " & username & vbCRLF 
    script = script & password & vbCRLF 
    script = script & "cd " & """" & remoteDir & """" & vbCRLF 
    script = script & "binary" & vbCRLF 
    script = script & "prompt n" & vbCRLF 
    script = script & "put " & """" & localFile & """" & vbCRLF 
    script = script & "quit" & vbCRLF 


    Set textFile = fso.CreateTextFile(scriptFile, True) 
    textFile.WriteLine(script) 



    ' bWaitOnReturn set to TRUE - indicating script should wait for the program 
    ' to finish executing before continuing to the next statement 
    shell.Run "%comspec% /c FTP -n -s:" & scriptFile & " > " & outputFile, 0, TRUE 
    Wscript.Sleep 10 
    ' open standard output temp file read only, failing if not present 
    Set textFile = fso.OpenTextFile(outputFile, 1, 0, -2) 
    results = textFile.ReadAll 
    textFile.Close 

End If 

Next 

fso.DeleteFile(scriptFile) 
fso.DeleteFile(outputFile) 

Почему мы создаем временный файл с этим кодом,: S

Set shell = CreateObject("WScript.Shell") 

    tempDir = shell.ExpandEnvironmentStrings("%TEMP%") 
    ' temporary script file supplied to Windows FTP client 
    scriptFile = tempDir & "\" & fso.GetTempName 
    ' temporary file to store standard output from Windows FTP client 
    outputFile = tempDir & "\" & fso.GetTempName 


Set textFile = fso.CreateTextFile(scriptFile, True) 
     textFile.WriteLine(script) 



     ' bWaitOnReturn set to TRUE - indicating script should wait for the program 
     ' to finish executing before continuing to the next statement 
     shell.Run "%comspec% /c FTP -n -s:" & scriptFile & " > " & outputFile, 0, TRUE 
     Wscript.Sleep 10 
     ' open standard output temp file read only, failing if not present 
     Set textFile = fso.OpenTextFile(outputFile, 1, 0, -2) 
     results = textFile.ReadAll 
     textFile.Close 

Хотя я петля через скрипт, он должен загружать каждый txt-файл в текущий каталог, но он загружает только первый, почему это так?

При печати текущего т.е. файловой

MsgBox defaultfile 

он отображает имя каждого текстового файла внутри текущей папки, но загружать только первый файл.

ответ

5

Существует нет встроенного метода прямой автоматизации для FTP. Это на самом деле способ обхода сценариев. Ваш скрипт создает текстовый файл с инструкциями FTP. Затем он запускает FTP из командной строки, используя ключ -s. Этот -s-переключатель позволяет вам предоставить текстовый файл, содержащий команды сеанса для FTP.exe для выполнения перед закрытием. Поэтому, в то время как ваш скрипт фактически не автоматизирует FTP-программу напрямую, он имитирует автоматизацию, запустив FTP в «автоматическом режиме». Вы можете получить лучшее понимание, открыв командную строку и набрав ftp /?.

[EDIT] Прошу прощения, я пропустил ваш второй вопрос. Ваш скрипт загружает только первый файл, потому что он выполняет цикл вокруг метода CreateTextFile. Этот метод не работает после первой попытки, потому что файл уже существует. То, что вам действительно нужно делать, - это объединить ваши файлы во временный файл, а затем выполнить FTP только один раз. Ваш веб-сервер также по достоинству оценят перерыв.

Dim fso, folder, files, strPath 
Set fso = CreateObject("Scripting.FileSystemObject") 

strPath = "E:/Test" 
Set folder = fso.GetFolder(strPath) 
Set files = folder.Files 

Const hostname = "ftp.domain.com" 
Const port = 21 
Const username = "username" 
Const password = "password" 
Const remoteDir = "/" 
Const useDefaultsExclusively = True 
Const skipConfirmation = True 

tempDir = shell.ExpandEnvironmentStrings("%TEMP%") 
' temporary script file supplied to Windows FTP client 
scriptFile = tempDir & "\" & fso.GetTempName 
' temporary file to store standard output from Windows FTP client 
outputFile = tempDir & "\" & fso.GetTempName 

Set textFile = fso.CreateTextFile(scriptFile, True) 

'input script 
textFile.WriteLine("open " & hostname & " " & port) 
textFile.WriteLine("user " & username) 
textFile.WriteLine(password) 
textFile.WriteLine("cd " & Chr(34) & remoteDir & Chr(34)) 
textFile.WriteLine("binary") 
textFile.WriteLine("prompt n") 

For Each item In files 
    If InStr(1, item.Name, "txt") <> 0 Then 
     textFile.WriteLine("put " & Chr(34) & item.Path & "\" & item.Name & Chr(34)) 
    End If 
Next 

textFile.WriteLine("quit") 
textFile.Close 

Set shell = CreateObject("WScript.Shell") 
' bWaitOnReturn set to TRUE - indicating script should wait for the program 
' to finish executing before continuing to the next statement 
shell.Run "%comspec% /c FTP -n -s:" & scriptFile & " > " & outputFile, 0, True 
WScript.Sleep 10 
' open standard output temp file read only, failing if not present 
Set textFile = fso.OpenTextFile(outputFile, 1, 0, -2) 
results = textFile.ReadAll 
textFile.Close 

fso.DeleteFile(scriptFile) 
fso.DeleteFile(outputFile) 
Смежные вопросы