powershellautomationuploadsftpwinscp

Upload file to SFTP using PowerShell


We were asked to set up an automated upload from one of our servers to an SFTP site. There will be a file that is exported from a database to a filer every Monday morning and they want the file to be uploaded to SFTP on Tuesday. The current authentication method we are using is username and password (I believe there was an option to have key file as well but username/password option was chosen).

The way I am envisioning this is to have a script sitting on a server that will be triggered by Windows Task scheduler to run at a specific time (Tuesday) that will grab the file in question upload it to the SFTP and then move it to a different location for backup purposes.

For example:

I tried few things at this point WinSCP being one of them as well as SFTP PowerShell Snap-In but nothing has worked for me so far.

This will be running on Windows Server 2012R2.
When I run Get-Host my console host version is 4.0.

Thanks.


Solution

  • There isn't currently a built-in PowerShell method for doing the SFTP part. You'll have to use something like psftp.exe or a PowerShell module like Posh-SSH.

    Here is an example using Posh-SSH:

    # Set the credentials
    $Password = ConvertTo-SecureString 'Password1' -AsPlainText -Force
    $Credential = New-Object System.Management.Automation.PSCredential ('root', $Password)
    
    # Set local file path, SFTP path, and the backup location path which I assume is an SMB path
    $FilePath = "C:\FileDump\test.txt"
    $SftpPath = '/Outbox'
    $SmbPath = '\\filer01\Backup'
    
    # Set the IP of the SFTP server
    $SftpIp = '10.209.26.105'
    
    # Load the Posh-SSH module
    Import-Module C:\Temp\Posh-SSH
    
    # Establish the SFTP connection
    $ThisSession = New-SFTPSession -ComputerName $SftpIp -Credential $Credential
    
    # Upload the file to the SFTP path
    Set-SFTPFile -SessionId ($ThisSession).SessionId -LocalFile $FilePath -RemotePath $SftpPath
    
    #Disconnect all SFTP Sessions
    Get-SFTPSession | % { Remove-SFTPSession -SessionId ($_.SessionId) }
    
    # Copy the file to the SMB location
    Copy-Item -Path $FilePath -Destination $SmbPath
    

    Some additional notes:

    That should give you a decent starting point.