Call multiple commands from powershell e.g psftp

2019-02-10 01:00发布

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"

1条回答
对你真心纯属浪费
2楼-- · 2019-02-10 01:38

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.

查看更多
登录 后发表回答