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"
The commands can be in one PowerShell invocation by using a SEMICOLON at the end of each line. You need just one execution of PowerShell, and multiple commands passed to it. Each of those commands should be separated with semicolons, ; , and should all be enclosed within one doublequoted -Command argument.
Users that have opened PSFTP from command line must need to establish a link to the SFTP server. To open a connection, type the following command “open host.name.” However, if a user wants to state a particular username as well, they have to write the following command “open [email protected]”.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With