4

I have searched and read a lot about downloading SSL FTP files in PowerShell... But how do I upload them? I have a filename I need to upload each day and I get errors that I am not logged in. I'm currently uploading to other FTP sites like this:

$Filename = "myfile.txt"
$FullPath = "\\server\share\$Filename"
$ftp = "ftp://user:pass@ftp.domain.com/$Filename"
$ftpWebClient = New-Object System.Net.WebClient
$ULuri= New-Object System.URI($ftp)
$ftpWebClient.UploadFile($ULuri, $FullPath)

Do I need to create a whole new block of code for the SSL FTP upload, or do I just need to make minor adjustments to this code?

Thanks!

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
user1467163
  • 169
  • 1
  • 5
  • 13

2 Answers2

8

I use the WinSCP DLL to do this stuff. Check out some examples here: http://winscp.net/eng/docs/library#powershell

Here's some of my sample code.

[Reflection.Assembly]::LoadFrom("D:\WinSCP.dll") | Out-Null
$sessionOptions = New-Object WinSCP.SessionOptions
$sessionOptions.Protocol = [WinSCP.Protocol]::Sftp
$sessionOptions.HostName = "192.168.1.120"
$sessionOptions.UserName = "user"
$sessionOptions.Password = "pass"
$session = New-Object WinSCP.Session
$session.Open($sessionOptions)

#upload stuff here, check the link for detail on how, and use powershell to populate your file list!

$session.Dispose()
Chris N
  • 7,239
  • 1
  • 24
  • 27
  • 4
    SFTP is not FTP over TLS/SSL. For FTP over TLS/SSL use `$sessionOptions.Protocol = [WinSCP.Protocol]::Ftp` and `$sessionOptions.FtpSecure = [WinSCP.FtpSecure]::Explicit` – Martin Prikryl Jun 29 '17 at 06:33
  • Just to add to @MartinPrikryl's comment, you will also need to either set `$sessionOptions.GiveUpSecurityAndAcceptAnyTlsHostCertificate = $true` or set `$sessionOptions.TlsHostCertificateFingerprint = "00:11:22:..."` – Mort Oct 21 '22 at 11:08
  • 1
    @Mort You need that only if the server's certificate is not signed by a trusted authority. – Martin Prikryl Oct 22 '22 at 05:16
6

As you are already using the WebClient class from the .NET framework in your script, I suggest you create a derived version from WebClient that supports FTP over TLS, by embedding C# code in PowerShell:

$typeDefinition = @"
using System;
using System.Net;
public class FtpClient : WebClient
{
    protected override WebRequest GetWebRequest(Uri address)
    {
        FtpWebRequest ftpWebRequest = base.GetWebRequest(address) as FtpWebRequest;
        ftpWebRequest.EnableSsl = true;
        return ftpWebRequest;
    }
}
"@

Add-Type -TypeDefinition $typeDefinition
$ftpClient = New-Object FtpClient
$ftpClient.UploadFile("ftp://your-ftp-server/yourfile.name", "C:\YourLocalFile.name")
h0r41i0
  • 234
  • 4
  • 5