title: PowerShell to use WinSCP .NET assembly with secure credentials
body: <p>I'm trying to use WinSCP .NET assembly with secure credential, when the password secured in external file.</p>
  
  
  
  <pre class="lang-powershell prettyprint-override"><code># Load WinSCP .NET assembly
  Add-Type -Path "D:\WinSCPnet.dll"
  
  # Setup session options
  $sessionOptions = New-Object WinSCP.SessionOptions
  $sessionOptions.Protocol = [WinSCP.Protocol]::Sftp
  
  # Env
  $sessionOptions.HostName = "blabla.com"
  $sessionOptions.UserName = "UUUU"
  #$sessionOptions.Password = "PPPP"
  $sessionOptions.SshHostKeyFingerprint = "XXXXXXXXX"
  $remotePath = "/home/UUUU/"
  </code></pre>
  
  <p>With hard coded password its working. If I would like to use securestring for the password, how should I do that?</p>
  
  <p>I tried:</p>
  
  <pre class="lang-powershell prettyprint-override"><code>read-host -assecurestring | convertfrom-securestring | out-file D:\securestring.txt
  </code></pre>
  
  <p>To keep the secure password in a file. Then, in my script, I get it back:</p>
  
  <pre class="lang-powershell prettyprint-override"><code>$sessionOptions.Password = get-Content D:\securestring.txt | convertto-securestring
  
  $Cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $sessionOptions.UserName, $sessionOptions.Password}
  </code></pre>
  
  <p>But it's not working...</p>