Gorgo.Live.ToString()

Mariusz, Gorzoch tech Blog

Upload of files to FTPS from PowerShell

leave a comment »

Recently I’ve updated my PowersShell script to upload files to FTPS (FTP over SSL) server. Below you can find that script. Most important change in comparison to previous one is around the way I read and send data. In previous version this was done thru read of entire file into memory and then just sent it from the buffer. That of course could cause problems in case of large files. New approached uses small buffer (=4096) and send that in peace’s. To find more details about that script please refer to my previous post

[Net.ServicePointManager]::ServerCertificateValidationCallback={$true}
$Dir = "D:\FolderWithBackupFilesToMove"
foreach($item in (dir $dir))
{
    write-output "————————————–"
    $fileName = $item.FullName
    write-output $fileName
    $ftp = [System.Net.FtpWebRequest]::Create("ftp://some.ftp.server.com/someRootFolder/"+$item.Name)
    $ftp = [System.Net.FtpWebRequest]$ftp
    $ftp.UsePassive = $true
    $ftp.UseBinary = $true
    $ftp.EnableSsl = $true
    $ftp.Credentials = new-object System.Net.NetworkCredential("UserName","Password")
    $ftp.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
    $rs = $ftp.GetRequestStream()
   
    $reader = New-Object System.IO.FileStream ($fileName, [IO.FileMode]::Open, [IO.FileAccess]::Read, [IO.FileShare]::Read)
    [byte[]]$buffer = new-object byte[] 4096
    [int]$count = 0
    do
    {
        $count = $reader.Read($buffer, 0, $buffer.Length)
        $rs.Write($buffer,0,$count)
    } while ($count -gt 0)
    $reader.Close()
    $rs.Close()
    write-output "+transfer completed"
   
    $item.Delete()
    write-output "+file deleted"
}

have fun

Advertisements

Written by Mariusz Gorzoch

7 January 2014 at 11:07

Posted in Powershell

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: