PowerShell SecurePassword

Advertisement

powershell-489
Joined:
Posts:
2

PowerShell SecurePassword

Good Morning,
I want to copy files from Windows Server to SSH Server via WinSCP Script. My goal is to encrypt the login password of the SSH server in the script. I tried to encrypt the password as in this tutorial: https://winscp.net/eng/docs/guide_protecting_credentials_for_automation#powershell

First I converted the plaintext password in a separate PowerShell with this command:
Read-Host -AsSecureString | ConvertFrom-SecureString
Now I have copied the generated string into my XML file:
<Configuration>
  <UserName>username</UserName>
  <Password>01000000d08c9.....</Password>
</Configuration>
now I started my PowerShell script:
This is my script:
try
{
# Read XML configuration file
    [xml]$config = Get-Content "C:\temp\config.xml"
    # Load WinSCP .NET assembly
    Add-Type -Path "path-to-winscp\WinSCPnet.dll"
 
    # Setup session options
    $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
    $sessionOptions.SecurePassword = ConvertTo-SecureString $config.Configuration.Password
        Protocol = [WinSCP.Protocol]::Scp
        HostName = "my-ip-address"
        UserName = $config.Configuration.UserName
        Password = $sessionOptions.SecurePassword
        SshHostKeyFingerprint = "ssh-ed25519 255 my-finger-print"
    }
 
    $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("my-source-path\myfile-*", "my-destination-path", $False, $transferOptions)
 
        # Throw on any error
        $transferResult.Check()
 
        # Print results
        foreach ($transfer in $transferResult.Transfers)
        {
            Write-Host "Upload of $($transfer.FileName) succeeded"
        }
    }
    finally
    {
        # Disconnect, clean up
        $session.Dispose()
    }
 
    exit 0
}
catch
{
    Write-Host "Error: $($_.Exception.Message)"
    exit 1
}
I get the following error:
Error: The System.Security.SecureString element was not found for the specified .NET object.
What did I do wrong?

Reply with quote

Advertisement

martin
Site Admin
martin avatar
Joined:
Posts:
40,605
Location:
Prague, Czechia

Re: PowerShell SecurePassword

It's just a wrong PowerShell code syntax.
This is correct syntax:
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
    SecurePassword = ConvertTo-SecureString $config.Configuration.Password
    ...
}

Reply with quote

Advertisement

You can post new topics in this forum