I have a Powershell script I'm using to log in to an SFTP server, and passing the credentials for login, via the "Convertto-SecureString" method. I generated the string on the same machine and user account that will be running the script, and pasted the string in to an XML file, so that it can be referenced in a static location. When I run the script, manually, as the service account in question, it works without issue. However, running it in Windows Task Scheduler as the same account, yields the error: Connection has been unexpectedly closed. Server sent command exit status 0.
My code block is below:
# Connect to SFTP server for Upload
# Load WinSCP .NET assembly
Add-Type -Path "C:\Program Files (x86)\WinSCP\WinSCPnet.dll"
# Read XML configuration file
[xml]$config = Get-Content ".\config.xml"
# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions
$sessionOptions.Protocol = [WinSCP.Protocol]::Sftp
$sessionOptions.PortNumber = "22"
$sessionOptions.HostName = "SFTP Server Domain Name"
$sessionOptions.UserName = $config.Configuration.UserName
$sessionOptions.SshHostKeyFingerprint = "ssh-rsa 2048 Server:Thumb:Print"
# Use only if authenticating with a Password
$sessionOptions.SecurePassword = $config.Configuration.Password | ConvertTo-SecureString