我想使用PowerShell自动化脚本将最近的XML文件从我的本地文件夹上传到FTP服务器。我通过互联网搜索,发现它可以通过PowerShell中的WinSCP实现。但我发现文档很混乱。任何人都有任何信息如何使用PowerShell ISE或WinSCP实现这一目标?
我想将从本地文件夹到晚上10点时间戳的ABCDEF.XML
上传到FTP服务器。
答案 0 :(得分: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 -File switch of Get-ChildItem.
$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
$sourcePath = Join-Path $localPath $latest.Name
$session.PutFiles(
[WinSCP.RemotePath]::EscapeFileMask($sourcePath),
[WinSCP.RemotePath]::CombinePaths($remotePath, "*")).Check()
}
finally
{
# Disconnect, clean up
$session.Dispose()
}
exit 0
}
catch
{
Write-Host "Error: $($_.Exception.Message)"
exit 1
}
如果您发现任何令人困惑的代码,您必须更具体。
虽然更容易使用普通Windows批处理文件中的plain WinSCP script with its -latest
switch(如果您愿意,也可以使用PowerShell)。