como copiar arquivos do SFTP para o host local (windows server) usando o powershell

0

Estou usando o comando shell abaixo para copiar o arquivo do servidor "SFTP" para o windows server. por algum motivo, o Script não está funcionando, por favor, ajude

# 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 
    
por Ealhiary 22.03.2015 / 12:49

1 resposta

2

Ok, além de descobrir que o nome da função estava errado, o que fez com que o script não copiasse seus arquivos, eu gostaria de mostrar a você o 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 

O seguinte é o mesmo, mas com splatting. Ele faz uso de um hashtable que pode ser passado para uma função desde que todas as chaves hashtable (as strings antes do sinal =) correspondam aos nomes dos parâmetros da função:

$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

Como sua função define Remove para true por padrão, é redundante especificá-la. Meu exemplo mostra que você pode misturar e combinar parâmetros normais com a hashtable usada para splatting.

    
por 22.03.2015 / 14:13