powershellsftpwinscpwinscp-net

Configure WinSCP PowerShell script to also include a private key


I would like to add a private key to the code found from the WinSCP website. Based on https://winscp.net/eng/docs/library_example_delete_after_successful_download

# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
    Protocol = [WinSCP.Protocol]::Sftp
    HostName = "example.com"
    UserName = "user"
    Password = "mypassword"
    SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx..."
}
 
$session = New-Object WinSCP.Session
 
# Connect
$session.Open($sessionOptions)

How can I achieve this and where could I fit this in?
Thanks in advance.


Solution

  • Use SessionOptions.SshPrivateKeyPath (or SessionOptions.SshPrivateKey):

    # Setup session options
    $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
        Protocol = [WinSCP.Protocol]::Sftp
        HostName = "example.com"
        UserName = "user"
        SshPrivateKeyPath = "C:\path\to\mykey.ppk"
        SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx..."
    }