在PowerShell中使用WinSCP模块创建SFTP连接功能

时间:2019-05-07 07:10:21

标签: powershell winscp

我对WinSCP模块有问题。我已经创建了一个SFTP连接功能,希望在其他脚本中使用。 问题是当我运行该函数时,它给我一条错误消息:

New-WinSCPSessionOption : Cannot validate argument on parameter 'SshPrivateKeyPath'. Unable to find part of Path: "Z:\my_key.ppk "

+ ...    $sessionOption = New-WinSCPSessionOption @parameter_sessionOptions
+                                                 ~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo          : InvalidData: (:) [New-WinSCPSessionOption], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,New-WinSCPSessionOption

此消息后,脚本将向前运行并执行所需的操作。 如果我逐行运行命令(不是作为函数运行),则不会出现任何错误消息。 我想念什么?

######################## Importing WinSCP module    ##########################

 Import-Module -Name "C:\Program Files (x86)\WindowsPowerShell\Modules\WinSCP" -Force 

############################## SFTP connection ###############################

function Start-SFTPConnection {
[cmdletbinding()]
param (
    [Parameter(Mandatory=$true)][string]$xmlFile,
    [Parameter(Mandatory=$true)][string]$MountDrive
    )

    [xml]$config = Get-Content $xmlFile -ErrorAction Stop

    [string]$serverName = $config.Configuration.HostName
    [string]$UserName = $config.Configuration.UserName
    [string]$remotePath = $config.Configuration.RemotePath
    [string]$SshHostKeyFingerprint = $config.Configuration.SshHostKeyFingerprint
    [string]$SshPrivateKeyPath = $config.Configuration.SshPrivateKeyPath

    New-PSDrive -Name "P" -PSProvider FileSystem -Root $MountDrive -Persist -ErrorAction Stop -Verbose

   $MyCredential = 
    New-Object System.Management.Automation.PSCredential ($UserName,(new-object System.Security.SecureString)) -ErrorAction Stop 

    $parameter_sessionOptions = @{
        'Credential' = $MyCredential;
        'HostName' = $serverName;
        'Protocol' = 'SFTP';
        'SshHostKeyFingerprint' = $SshHostKeyFingerprint;
        'SshPrivateKeyPath' = $SshPrivateKeyPath;
        'ErrorAction' = 'Stop';
     }

    Test-Path -Path $SshPrivateKeyPath

    if ((Test-Path -Path $SshPrivateKeyPath)) {

    $sessionOption = New-WinSCPSessionOption @parameter_sessionOptions 

    $session = New-WinSCPSession -SessionOption $sessionOption -Verbose

        $parameter_remoteFiles = @{
            'WinSCPSession' = $session;
            'Path' = $remotePath;
            'File' = $true;
            'Recurse' = $True;
            'ErrorAction' = 'Stop';            
        }
        [System.Array]$remoteFiles =
            Get-WinSCPChildItem @parameter_remoteFiles -Verbose

        $remoteFiles.FullName

    }
else {
    Write-Host "$SshPrivateKeyPath path not exists"
}
Remove-PSDrive -Name "P" -PSProvider FileSystem -Force -ErrorAction Stop -Verbose

Remove-Module -Name "WinSCP" -Force 
}

Start-SFTPConnection -xmlFile 'path' -MountDrive 'path'

0 个答案:

没有答案