将文件复制到FTP并使用今天的日期进行存档 [英] Copy files to FTP and archive with today's date

查看:87
本文介绍了将文件复制到FTP并使用今天的日期进行存档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I need to create a script that does the following:

  1. 将文件夹中的所有文件复制到FTP站点.
  2. 如果复制成功,则将文件移至存档.
  3. 档案应该是一个带有今天日期的新创建的文件夹(这样我们就知道它们何时传输了).

我试图蚕食其他脚本来使某些东西正常工作,但是我什么也没找到,所以我需要一些已经在此工作了几个小时的帮助.

I've tried to cannibalise other scripts to get something to work but I'm not getting anywhere so I need some help I've been working on this for hours.

我之所以使用WinSCP DLL,仅是因为我的其他(工作)脚本使用了需要它的SFTP.我知道普通的FTP不能,但是我找不到任何易于传输的代码,因此请尝试对其进行修改.

I'm using the WinSCP DLL only because my other (working) script uses SFTP which needs it. I know normal FTP doesn't but I couldn't find any easily transferrable code so trying to modify that instead.

所以,这是我的代码,即使没有运行,也没关系正确运行,有人可以帮我把代码弄对吗?抱歉,这有点混乱.

So, here's the code I have, which doesn't even run, never mind run properly, can someone help me get it right? Sorry it's a bit of a mess.

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来简化它,我只是希望它能正常工作.

So there's the code. I'm happy to use built in PowerShell for the FTP side to simplify it, I just want it to work.

推荐答案

我不确定您对代码有什么担心.设置 $ folder :

I'm not sure what's your concern with the code. It looks pretty much ok, except for a syntax error, when setting $folder:

您为什么还要尝试使用 $ _.CreationTime 作为文件夹时间戳?只需使用当前日期即可:

Why are you even trying to use $_.CreationTime as folder timestamp? Just use current date:

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

请参见WinSCP文档中的在PowerShell中格式化时间戳.

See Formatting timestamps in PowerShell in WinSCP documentation.

我也看不到在 params 块中设置 $ folder $ backupPath 的意义.将其移动到 params 块之后.如果仍然要这样做,则在 $ folder 赋值后会丢失逗号.

Also I do not see a point of setting $folder and $backupPath in the params block. Move it after the params block. If you want this anyway, you are missing a comma after the $folder assignment.

除此之外,您的代码应该可以工作.

Other than that, your code should work.

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

You cannot simplify it by using the built-in PowerShell (or rather .NET) FTP functionality, as it does not have as powerful commands as WinSCP .NET assembly.

我将代码编写为:

$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
}

基于成功上传后将本地文件移动到其他位置.

这篇关于将文件复制到FTP并使用今天的日期进行存档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆