【问题标题】:Upload most recent file to FTP server using PowerShell ISE or WinSCP使用 PowerShell ISE 或 WinSCP 将最新文件上传到 FTP 服务器
【发布时间】:2018-08-30 17:28:44
【问题描述】:
我想使用 PowerShell 自动化脚本将最近的 XML 文件从我的本地文件夹上传到 FTP 服务器。我在网上搜索,发现可以通过PowerShell中的WinSCP来实现。任何人都知道如何使用 PowerShell ISE 或 WinSCP 来实现这一目标?
我想将具有晚上 10 点时间戳的ABCDEF.XML 从我的本地文件夹上传到 FTP 服务器。
【问题讨论】:
标签:
.net
powershell
ftp
winscp
winscp-net
【解决方案1】:
您的确切任务有 WinSCP 示例:Upload the most recent file in PowerShell。
您需要做的唯一修改是脚本用于 SFTP,而您需要 FTP。虽然变化微不足道且非常明显:
try
{
# Load WinSCP .NET assembly
Add-Type -Path "WinSCPnet.dll"
# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::Ftp
HostName = "example.com"
UserName = "user"
Password = "mypassword"
}
$session = New-Object WinSCP.Session
try
{
# Connect
$session.Open($sessionOptions)
$localPath = "c:\toupload"
$remotePath = "/home/user"
# Select the most recent file.
# The !$_.PsIsContainer test excludes subdirectories.
# With PowerShell 3.0, you can replace this with Get-ChildItem -File switch
$latest =
Get-ChildItem -Path $localPath |
Where-Object {!$_.PsIsContainer} |
Sort-Object LastWriteTime -Descending |
Select-Object -First 1
# Any file at all?
if ($latest -eq $Null)
{
Write-Host "No file found"
exit 1
}
# Upload the selected file
$session.PutFiles(
[WinSCP.RemotePath]::EscapeFileMask($latest.FullName),
[WinSCP.RemotePath]::Combine($remotePath, "*")).Check()
}
finally
{
# Disconnect, clean up
$session.Dispose()
}
exit 0
}
catch
{
Write-Host "Error: $($_.Exception.Message)"
exit 1
}
如果您发现代码中有任何令人困惑的地方,则必须更具体。
虽然更简单的是从普通的 Windows 批处理文件(或 PowerShell,如果您愿意)使用 plain WinSCP script with its -latest switch。