Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call multiple commands from powershell e.g psftp

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"
like image 203
Afroz Avatar asked Dec 19 '11 01:12

Afroz


People also ask

How do I run multiple commands in PowerShell?

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.

How use PSFTP command line?

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]”.


1 Answers

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.

like image 94
OldFart Avatar answered Oct 02 '22 08:10

OldFart