从 powershell 调用多个命令,例如 psftp

发布于 2024-12-21 18:02:42 字数 412 浏览 0 评论 0原文

我正在尝试使用 psftp.exe (putty) 从 powershell 通过 SFTP 传输文件。我可以运行单个命令,例如 open,但我需要更改默认目录,然后放置文件。以下代码将我带到 psftp,但忽略从 cd .. 到 bye 的行。我想我可以运行一个包含 sftp 命令的批处理文件,但如果可能的话我想使用 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"

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"

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

吹梦到西洲 2024-12-28 18:02:42

尝试一下:

$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"

回答评论中的问题:

第一部分,“$cmd |”将 $cmd 的内容通过管道传递给后面的命令。由于它是外部程序(与 cmdlet 或函数相反),因此它将 $cmd 的内容发送到外部程序的 stdin。

“& $path”部分表示将 $path 的内容视为命令或程序名并执行它。

该行的其余部分作为命令行参数传递给外部程序。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文