6

I am trying to SFTP a file from powershell using psftp.exe (putty). I can run single command such as open but I need to change the default directory and then put the file. The following code takes me to psftp but ignores lines from cd .. to bye. I guess I can run a batch file which has the sftp commands but if possible I want to accomplish using powershell.

$file = "C:\Source\asdf.csv"
$user = "user"
$pass = "pass"
$hst = "host"
$path="C:\ProgramFiles\psftp.exe"
$cmd = @"
-pw $pass $user@$hst
cd ..
cd upload
put $file
bye
"@

invoke-expression "$path $cmd"
Afroz
  • 1,017
  • 2
  • 12
  • 24

1 Answers1

6

Give this a try:

$file = "C:\Source\asdf.csv"
$user = "user"
$pass = "pass"
$hst = "host"
$path="C:\ProgramFiles\psftp.exe"
$cmd = @(
"cd ..",
"cd upload",
"put $file",
"bye"
)

$cmd | & $path -pw $pass "$user@$hst"

In answer to the questions in the comment:

The first part, "$cmd |" pipes the contents of $cmd to the command that follows. Since it is an external program (as opposed to a cmdlet or function) it will send the contents of $cmd to stdin of the external program.

The "& $path" part says to treat the contents of $path as a command or program name and execute it.

The rest of the line is passed to the external program as command line arguments.

OldFart
  • 2,411
  • 15
  • 20
  • This works great. so we put the commands in an array and you lost me from there. why do we have & $path -pw $pass.. at the end and $cmd in the beginning? and what does & accomplish? – Afroz Dec 20 '11 at 01:13
  • hey @OldFart is there a way to capture error message from the command prompt, right now when I check $lastexitcode is 0 – Afroz Jan 06 '12 at 23:40