【发布时间】:2018-05-08 11:40:56
【问题描述】:
我需要创建一个执行以下操作的脚本:
- 将文件夹中的所有文件复制到 FTP 站点。
- 如果复制成功,请将文件移动到存档中。
- 存档应该是一个新创建的文件夹,其中包含今天的日期(以便我们知道它们的传输时间)。
我试图蚕食其他脚本以使某些东西起作用,但我没有得到任何帮助,所以我需要一些帮助,我已经为此工作了几个小时。
我使用 WinSCP DLL 只是因为我的其他(工作)脚本使用了需要它的 SFTP。我知道普通的 FTP 没有,但我找不到任何易于传输的代码,所以尝试修改它。
所以,这是我拥有的代码,它甚至无法运行,更不用说正常运行了,有人可以帮我解决吗?抱歉有点乱。
param (
$localPath = "c:\test\source",
$remotePath = "/upload",
$folder = ($_.CreationTime | Get-Date -Format yyyyMMdd)
# not sure this works but don't see how to point the destination
# to the newly created folder
$backupPath = "c:\test\destination\$folder"
)
try
{
# Load WinSCP .NET assembly
Add-Type -Path "C:\Windows\System32\WindowsPowerShell\v1.0\WinSCPnet.dll"
# Setup session options
$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
Protocol = [WinSCP.Protocol]::ftp
HostName = "xxxxxxxx"
UserName = "xxxxxxxx"
Password = "xxxxxxxx"
}
$session = New-Object WinSCP.Session
try
{
# Connect
$session.Open($sessionOptions)
# Upload files, collect results
$transferResult = $session.PutFiles($localPath, $remotePath)
# Iterate over every transfer
foreach ($transfer in $transferResult.Transfers)
{
# Success or error?
if ($transfer.Error -eq $Null)
{
# If today's folder doesn't exist, create it
if (!(Test-Path $BackupPath))
{
New-Item -ItemType Directory -Force -Path $BackupPath
}
Write-Host ("Upload of {0} succeeded, moving to Uploaded folder" -f
$transfer.FileName)
# Upload succeeded, move source file to backup
Move-Item $transfer.FileName $backupPath
}
else
{
Write-Host ("Upload of {0} failed: {1}" -f
$transfer.FileName, $transfer.Error.Message)
}
}
}
finally
{
# Disconnect, clean up
$session.Dispose()
}
exit 0
}
catch [Exception]
{
Write-Host ("Error: {0}" -f $_.Exception.Message)
exit 1
}
所以有代码。我很高兴为 FTP 端使用内置的 PowerShell 来简化它,我只是希望它能够工作。
【问题讨论】:
标签: powershell ftp winscp winscp-net