Search code examples
powershellwinscp

How to pass parameters in PowerShell script which executes in WinSCP command?


I have a PowerShell script

cd "C:\Program Files (x86)\WinSCP"
. .\WinSCP.exe /console /script="L:\Work\SAS Data\FTP\local2remote.txt"  /log=log.txt

It calls WinSCP command file

option batch on
open ftp://user:pass@host -passive=on
lcd "J:\Work\SAS Data\Roman\Lists"
put target.csv
exit

I want to convert "J:\Work\SAS Data\Roman\Lists" to a parameter in the PowerShell script where the parameter can be passed in the txt file. Same goes for the file target.csv. Any help appreciated.


Solution

  • The easiest way (and one that doesn't involve writing a temporary script file) would be to switch to /command for WinSCP:

    # You don't need the . operator to run external programs
    .\WinSCP.exe /console /log=log.txt /command `
      'open ftp://user:pass@host -passive=on' `
      'lcd "J:\Work\SAS Data\Roman\Lists"' `
      'put target.csv' `
      'exit'
    

    Now you have a much easier time incorporating script parameters:

    param([string] $Path, [string] $FileName)
    
    & 'C:\Program Files (x86)\WinSCP\WinSCP.exe' /console /log=log.txt /command `
      'open ftp://user:pass@host -passive=on' `
      "lcd `"$Path`"" `
      "put `"$FileName`"" `
      'exit'
    

    However, you can of course, still write a command file and pass that:

    $script = Join-Path $Env:TEMP winscp-commands.txt
    
    "open ftp://user:pass@host -passive=on
    lcd ""$Path""
    put ""$FileName""
    exit" | Out-File -Encoding Default $script
    
    & 'C:\Program Files (x86)\WinSCP\WinSCP.exe' /console /log=log.txt /script=$script
    Remove-Item $script