После некоторых экспериментов я разработал этот способ для автоматизации безопасной загрузки FTP в PowerShell. Этот скрипт запускается с public test FTP server, администрируемого Chilkat Software. Таким образом, вы можете скопировать и вставить этот код, и он будет работать без изменений.
$sourceuri = "ftp://ftp.secureftp-test.com/hamlet.zip"
$targetpath = "C:\hamlet.zip"
$username = "test"
$password = "test"
# Create a FTPWebRequest object to handle the connection to the ftp server
$ftprequest = [System.Net.FtpWebRequest]::create($sourceuri)
# set the request's network credentials for an authenticated connection
$ftprequest.Credentials =
New-Object System.Net.NetworkCredential($username,$password)
$ftprequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
$ftprequest.UseBinary = $true
$ftprequest.KeepAlive = $false
# send the ftp request to the server
$ftpresponse = $ftprequest.GetResponse()
# get a download stream from the server response
$responsestream = $ftpresponse.GetResponseStream()
# create the target file on the local system and the download buffer
$targetfile = New-Object IO.FileStream ($targetpath,[IO.FileMode]::Create)
[byte[]]$readbuffer = New-Object byte[] 1024
# loop through the download stream and send the data to the target file
do{
$readlength = $responsestream.Read($readbuffer,0,1024)
$targetfile.Write($readbuffer,0,$readlength)
}
while ($readlength -ne 0)
$targetfile.close()
Я нашел много полезной информации по этим ссылкам
Если вы хотите использовать подключение SSL необходимо добавить линия
$ftprequest.EnableSsl = $true
сценарий перед вызовом GetResponse(). Иногда вам может потребоваться справиться с сертификатом безопасности сервера, срок действия которого истек (например, я, к сожалению). На странице PowerShell Code Repository есть страница, для которой есть фрагмент кода. Первые 28 строк наиболее важны для загрузки файла.
это действует четвёртый вариант, который я должен был подумать о. Если вы будете знать имя файла раньше времени, то это, безусловно, хорошее решение, и вы должны принять его в качестве ответа. – EBGreen 2008-11-05 15:31:13