如何使用 powershell 将文件从 SFTP 复制到本地主机(windows 服务器)

如何使用 powershell 将文件从 SFTP 复制到本地主机(windows 服务器)

我正在使用以下 power shell 命令将文件从服务器“SFTP”复制到 windows 服务器。由于某种原因,脚本不起作用,请您帮忙

# 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 

答案1

好的,除了弄清楚函数名称错误导致脚本无法复制文件之外,我想向您展示 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 

以下代码与上述代码相同,但使用了 splatting。它利用了一个哈希表,只要所有哈希表键(= 符号之前的字符串)都与函数参数名称匹配,就可以将该哈希表传递给函数:

$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

由于您的函数默认将 Remove 设置为 true,因此指定它是多余的。我的示例向您展示了,您可以将普通参数与用于 splatting 的哈希表混合搭配。

相关内容