将文件复制到FTP并使用今天的日期存档

时间:2017-11-24 12:42:39

标签: powershell ftp winscp winscp-net

我需要创建一个执行以下操作的脚本:

  1. 将文件夹中的所有文件复制到FTP站点。
  2. 如果副本成功,请将文件移至存档。
  3. 存档应该是一个新创建的文件夹,其中包含今天的日期(因此我们知道它们何时被传输)。
  4. 我试图蚕食其他剧本以获得一些工作,但我没有得到任何地方,所以我需要一些帮助,我已经工作了好几个小时。

    我只使用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来简化它,我只是想让它工作。

1 个答案:

答案 0 :(得分:1)

我不确定您对代码的关注程度。在设置$folder

时,除了语法错误外,它看起来非常好

为什么你甚至试图使用$_.CreationTime作为文件夹时间戳?只需使用当前日期:

$folder = (Get-Date -Format "yyyyMMdd")

请参阅WinSCP文档中的Formatting timestamps in PowerShell

此外,我还没有在$folder块中设置$backupPathparams。在params块之后移动它。 如果您仍然需要此功能,则在$folder分配后您将缺少逗号。

除此之外,您的代码应该有效。

您无法使用内置的PowerShell(或更确切地说是.NET)FTP功能来简化它,因为它没有像WinSCP .NET程序集那样强大的命令。

我将代码编写为:

$localPath = "C:\source\local\path\*"
$remotePath = "/dest/remote/path/"
$folder = (Get-Date -Format "yyyyMMdd")
$backupPath = "C:\local\backup\path\$folder"

# If today's folder doesn't exist, create it
if (!(Test-Path $BackupPath))
{
    New-Item -ItemType Directory -Force -Path $BackupPath | Out-Null
}

try
{
    # Load WinSCP .NET assembly
    Add-Type -Path "WinSCPnet.dll"

    # Setup session options
    $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
        Protocol = [WinSCP.Protocol]::ftp
        HostName = "ftp.example.com"
        UserName = "username"
        Password = "password"
    }

    $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)
            {
                Write-Host "Upload of $($transfer.FileName) succeeded, moving to backup"
                # Upload succeeded, move source file to backup
                Move-Item $transfer.FileName $backupPath
            }
            else
            {
                Write-Host ("Upload of $($transfer.FileName) failed: " +
                    "$($transfer.Error.Message)")
            }
        }
    }
    finally
    {
        # Disconnect, clean up
        $session.Dispose()
    }

    exit 0
}
catch [Exception]
{
    Write-Host "Error: $($_.Exception.Message)"
    exit 1
}

基于Moving local files to different location after successful upload