WinSCP .NET assembly in PowerShell - Creating SessionOptions - The value supplied is not valid, or the property is read-only
Asked Answered
H

2

6

I'm trying to automate the transfer of files with WinSCP using PowerShell. I've installed .NET assembly. In the code I've added, I've taken out credentials and hostname for privacy and I'm also using the full path to WinSCPnet.dll. Here is the error I'm getting:

Error: The value supplied is not valid, or the property is read-only. Change the value, and then try again.

I'm getting this where $sessionOptions is defined on 5th line. Any ideas of what I could do to get this running?

try
{
    Add-Type -Path "WinSCPnet.dll"

    $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
        Protocol = [WinSCP.Protocol]::Sftp
        HostName = "HostName"
        UserName = "UserName"
        Password = "Password"
        SshHostKeyFingerprint = "ssh-rsa 2048 Fingerprint here"
    }

    $session = New-Object WinSCP.Session

    try
    {
        # Connect
        $session.Open($sessionOptions)

        # Upload files
        $transferOptions = New-Object WinSCP.TransferOptions
        $transferOptions.TransferMode = [WinSCP.TransferMode]::Binary

        $transferResult =
            $session.PutFiles("Source", "Destination", $False, $transferOptions)

        # Throw on any error
        $transferResult.Check()

        # Print results
        foreach ($transfer in $transferResult.Transfers)
        {
            Write-Host ("Upload of {0} succeeded" -f $transfer.FileName)
        }
    }
    finally
    {
        # Disconnect, clean up
        $session.Dispose()
    }

    exit 0 
    }
catch [Exception]
{
    Write-Host ("Error: {0}" -f $_.Exception.Message)
    exit 1
}
Halfassed answered 24/4, 2017 at 19:19 Comment(0)
T
8

The most probable explanation is that the value of SessionOptions.SshHostKeyFingerprint is invalid, no other property in your code is validated. See https://winscp.net/eng/docs/message_key_fingerprint_does_not_match

Use WinSCP GUI function to generate a code template to get the correct value.

Read also about Automatic host key verification.


If you need more help, you will have to show us the real value you are using (it's a fingerprint of a server public key, hence it is a public information, no need to hide it).

Terrie answered 24/4, 2017 at 20:12 Comment(0)
T
0

I've run into this recently and the issue turned out to be how the host key is shown in the connection profile. It was stripping off the trailing "=" character

Townshend answered 3/10, 2022 at 16:15 Comment(1)
In 5.21.3 the padding (=) is optional and is not contained in the generated code. I assume you are using latest version of WinSCP to generate code for an old version of WinSCP .NET assembly (which has the padding mandatory). Aren't you?Terrie

© 2022 - 2024 — McMap. All rights reserved.