how to copy files from SFTP to local host(windows server) using powershell

0

1

I am using the below power shell command to copy file from server "SFTP" to windows server. for some reason the Script is not working would you please help

# Scriptname.ps1
# send the files to Win-Server server F:\data\in
# Source files are deleted after transfer
# Local Path is the source path
# RemotePath is the flies destination path

Function Scriptname {
    Param(
        [Parameter(Mandatory=$true)]
        [ValidateNotNull()]
        [string] $Username = $(throw "Username parameter is required"),
        [Parameter(Mandatory=$true)]
        [ValidateNotNull()]
        [string] $Password = $(throw "Password parameter is required"),
        [Parameter(Mandatory=$true)]
        [ValidateNotNull()]
        [string] $HostName = $(throw "HostName parameter is required"),
        [Parameter(Mandatory=$true)]
        [ValidateNotNull()]
        [string] $RemotePath = $(throw "RemotePath parameter is required"),
        [Parameter(Mandatory=$true)]
        [ValidateNotNull()]
        [string] $LocalPath = $(throw "LocalPath parameter is required"),
        [Parameter(Mandatory=$true)]
        [ValidateNotNull()]
        [string] $SshHostKeyFingerprint = $(throw "SshHostKeyFingerprint parameter is required"),
        $Remove=$true

    )
    if( -not (Test-Path $LocalPath)) {
        throw("ERROR: Unable to locate LocalPath (path=${LocalPath})")
    }

    $Invocation = (Get-Variable MyInvocation -Scope 1).Value
    $SftpModuleDirectory = Split-Path $Invocation.MyCommand.Path

    [Reflection.Assembly]::LoadFrom("${SftpModuleDirectory}\WinSCPnet.dll") | Out-Null

    # Setup session options
    $sessionOptions = New-Object WinSCP.SessionOptions
    $sessionOptions.Protocol = [WinSCP.Protocol]::Sftp
    $sessionOptions.HostName = $HostName
    $sessionOptions.UserName = $Username
    $sessionOptions.Password = $Password
    $sessionOptions.SshHostKeyFingerprint = $SshHostKeyFingerprint #"ssh-rsa 1024 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"

    $session = New-Object WinSCP.Session

    # connect to FTP session
    try {

        $session.Open($sessionOptions)
        $session.GetFiles($remotePath, $localPath,$remove).Check() 

    } catch {

        if($_.Exception.ToString().Contains("Host key wasn't verified!")) {
            throw("invalid SshHostKeyFingerprint, unable to open session to FTP (host=${HostName}, SshHostKeyFingerprint=${SshHostKeyFingerprint})")
        }       
        elseif($_.Exception.ToString().Contains("No supported authentication methods available")) {
            throw("Unable to open session to FTP (host=${HostName}, username=${Username})")
        }       
    }

    finally
    {
        # Disconnect, clean up
        $session.Dispose()
    } 
}

$UserName = GetEnvironmentConfigValue "Scriptname.UserName"
$Password = GetEnvironmentConfigValue "Scriptname.Password"
$HostName = GetEnvironmentConfigValue "Scriptname.HostName"
$RemotePath = GetEnvironmentConfigValue "Scriptname.RemotePath"
$LocalPath = GetEnvironmentConfigValue "Scriptname.LocalPath"
$SshHostKeyFingerprint = GetEnvironmentConfigValue "Scriptname.SshHostKeyFingerprint"
$Remove=$true

Write-host "values: ${Username} ${Password} ${HostName} ${RemotePath} ${LocalPath} ${SshHostKeyFingerprint}"

SFTPUploadFiles $Username $Password $HostName $RemotePath $LocalPath $SshHostKeyFingerprint 

Ealhiary

Posted 2015-03-22T11:49:01.027

Reputation: 49

What error do you get, and what doesn't work specifically? – megamorf – 2015-03-22T11:57:02.633

the script run with no errors but no files were shown at the destination path, I am pretty sure that the files in the source path , thanks for your highly cooperation – Ealhiary – 2015-03-22T12:14:46.420

I assume all code after the function is yours (GetEnvironmentConfigValue, etc.), correct? Is it intended that the function is never called? The function is called scriptname in your example and not SFTPUploadFiles that you use in the last line of your code. – megamorf – 2015-03-22T12:30:19.503

correct, those values are saved in environment file where already declare . and i am calling them from the script. because i'm currently working on multi stages environment and need to change paths on every stage repeatedly , maybe i mixed in the script between copy from SFTP to local server (which in need to do )and copy from local to SFTP – Ealhiary – 2015-03-22T12:42:03.233

its work thanks , thanks a lot "The function is called scriptname in your example and not SFTPUploadFiles that you use in the last line of your code" that was the problem – Ealhiary – 2015-03-22T12:46:59.610

Answers

2

Ok, apart from figuring out that the function name was wrong which caused the script to not copy your files I'd like to show you Powershell splatting:

$UserName = GetEnvironmentConfigValue "Scriptname.UserName"
$Password = GetEnvironmentConfigValue "Scriptname.Password"
$HostName = GetEnvironmentConfigValue "Scriptname.HostName"
$RemotePath = GetEnvironmentConfigValue "Scriptname.RemotePath"
$LocalPath = GetEnvironmentConfigValue "Scriptname.LocalPath"
$SshHostKeyFingerprint = GetEnvironmentConfigValue "Scriptname.SshHostKeyFingerprint"
$Remove=$true

Write-host "values: ${Username} ${Password} ${HostName} ${RemotePath} ${LocalPath} ${SshHostKeyFingerprint}"

SFTPUploadFiles $Username $Password $HostName $RemotePath $LocalPath $SshHostKeyFingerprint 

The following is the same but with splatting. It makes use of a hashtable that can be passed to a function as long as all of the hashtable keys (the strings before the = sign) match the function parameter names:

$Parameters = @{
   "UserName" = GetEnvironmentConfigValue "Scriptname.UserName"
   "Password" = GetEnvironmentConfigValue "Scriptname.Password"
   "HostName" = GetEnvironmentConfigValue "Scriptname.HostName"
   "RemotePath" = GetEnvironmentConfigValue "Scriptname.RemotePath"
   "LocalPath" = GetEnvironmentConfigValue "Scriptname.LocalPath"
   "SshHostKeyFingerprint" = GetEnvironmentConfigValue "Scriptname.SshHostKeyFingerprint"
}


$Parameters

SFTPUploadFiles @Parameters -Remove:$false

Since your function sets Remove to true by default it's redundant to specify it. My example shows you, that you can mix and match normal parameters with the hashtable that's used for splatting.

megamorf

Posted 2015-03-22T11:49:01.027

Reputation: 1 494

hello ,would you please help me again i want to perform the same Job above , but i have only Username and privatekey.ppk is it possible to do that (Copy from SFTP to localhost) without password – Ealhiary – 2015-04-12T13:51:52.653