.net - 在批处理脚本中使用 Powershell 的 SFTP

标签 .net powershell batch-file ftp sftp

我有一个通过 schtasks 运行的批处理脚本每天晚上在不同的远程 Windows PC(Windows 7 32 位 SP1)上。这些 PC 需要将文件通过 FTP 传输到 Linux 服务器。目前使用 FTP,批处理脚本工作得很好。

现在 Linux 服务器正在更改为仅使用 SFTP。我想编写一个简短的 PowerShell 脚本,将相同的文件通过 SFTP 传输到服务器或从服务器传输——我已经安装了 Posh-Ssh,以便在这些 Windows 系统(PS 版本 5.1)上的 PowerShell 中使用。

目前,执行 FTP 的批处理脚本部分如下所示:

REM make temp file for FTP
echo open pos%STORE%               >  C:\temp\temp.txt
echo username                      >> C:\temp\temp.txt
echo password                      >> C:\temp\temp.txt
echo ascii                         >> C:\temp\temp.txt    
echo cd /path/to/use               >> C:\temp\temp.txt
echo put %USERDOMAIN%.ftp          >> C:\temp\temp.txt
echo put posdaily.txt posdaily.ftp >> C:\temp\temp.txt
echo get prod.txt                  >> C:\temp\temp.txt
echo get posdaily.ftp              >> C:\temp\temp.txt
echo quit                          >> C:\temp\temp.txt

REM **** FTP to put/get files from POS Server ****
echo First Try Connect to POS ....
ftp -iv -s:\temp\temp.txt >> C:\log\Daily.log  2>&1

有没有办法使用相同的temp.txt这是为了将用户名/密码/put/get 传递给使用 Posh-Ssh 的 PowerShell 脚本而创建的?我需要对 temp.txt 进行哪些更改文件?

我可以调用一个单独的批处理脚本来运行 PowerShell 脚本——我在之前的批处理脚本中已经这样做了——但我不确定如何编写 PowerShell 脚本——我将在 PowerShell 脚本中使用什么命令/命令来使用temp.txt 中的数据?

如果我让它在 PowerShell 中工作,我应该能够在需要执行相同操作的 C# 和 VB 脚本中调用相同的 PowerShell 脚本。

最佳答案

Is there a way to use this same temp.txt that's being created to pass the username/password/put/get to a Powershell script that uses Posh-Ssh?



你不能。 Posh-Ssh 是一个原生 PowerShell 模块,它不使用像 ftp 这样的脚本做。

同样正如@SomethingDark 已经评论的那样,没有必要为 SFTP 切换到 PowerShell。甚至对于 C#/VB.NET 也不行。从 C#/VB.NET 调用 PowerShell 脚本和批处理文件有什么区别?

对于批处理文件中的 SFTP,请参阅:
Secure FTP using Windows batch script

我的回答建议使用(我的)WinSCP SFTP client .
WinSCP 实际上可以使用与 ftp 类似(但不相同)的脚本。 .还有一个guide for converting ftp script to WinSCP script .

尽管如果您的目标是为 PowerShell/C#/VB.NET 提供相同/相似的代码,则最好使用 SFTP .NET 程序集。见 SFTP Libraries for .NET .

如果你想要一个原生 .NET 程序集,我会推荐 SSH.NET (尽管它的发展在过去几年中停止了)。而你实际上 use that already, don't you?

WinSCP 还 has .NET assembly – 但它不是一个完全原生的 .NET 程序集。另一方面,WinSCP GUI 可以 generate a code template for SFTP for all of PowerShell, C#, and VB.NET .

虽然您为什么不将您的传输功能实现到自定义程序集中并从所有 PowerShell/C#/VB.NET 中重用它?

关于.net - 在批处理脚本中使用 Powershell 的 SFTP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58564716/

相关文章:

windows - 批量合并单个制表符分隔文件中的 2 个 txt 文件

windows - 使用批处理文件设置 Windows 环境变量

c# - 作为 WCF 数据契约的 ObservableCollection 和 CollectionChanged 事件

c# - 如何使用 jQuery 设置列表框的值?

c# - 我可以用这种方式为所有派生的单例定义一个抽象类吗?

parsing - 使用 Powershell 解析二进制文件

powershell - 能否将 CmdletBinding 与未绑定(bind)参数结合使用?

javascript - 路由 "#"问题仍然发生angularjs

powershell - 在Powershell中递归重命名文件

batch-file - 运行命令后让 .bat 文件继续