1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
| function GetFilesListAsArray($user,$pass,$local_target,$ftp_uri,$subfolder)
{
# ftp address from where to download the files
$ftp_urix = $ftp_uri + $subfolder
$uri=[system.URI] $ftp_urix
$ftp=[system.net.ftpwebrequest]::Create($uri)
if($user)
{
$ftp.Credentials=New-Object System.Net.NetworkCredential($user,$pass)
}
#Get a list of files in the current directory.
#Use ListDirectoryDetails instead if you need date, size and other additional file information.
$ftp.Method=[system.net.WebRequestMethods+ftp]::ListDirectory
$ftp.UsePassive=$true
try
{
$response=$ftp.GetResponse()
$strm=$response.GetResponseStream()
$reader=New-Object System.IO.StreamReader($strm,'UTF-8')
$list=$reader.ReadToEnd()
$lines=$list.Split("`n")
return $lines
}
catch{
$_|fl * -Force
}
}
function DownloadFile ($sourceuri,$targetpath,$username,$password){
# 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
try
{
$targetfile = New-Object IO.FileStream ($targetpath,[IO.FileMode]::Create)
"File created: $targetpath"
[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()
}
catch
{
$_|fl * -Force
}
} |
Partager