使用WinSCP .NET程序集下载后移动(不复制)远程文件

问题描述 投票:1回答:2

我有这个脚本,可以下载所有.txt和.log文件。但是下载后,我需要将它们移动到服务器上的另一个目录。

到目前为止,我一直在收到类似“无法将”文件“移动到” /文件“之类的错误。

try
{
    # Load WinSCP .NET assembly
    Add-Type -Path "C:\Program Files (x86)\WinSCP\WinSCPnet.dll"

    # Setup session options
    $sessionOptions = New-Object WinSCP.SessionOptions
    $sessionOptions.Protocol = [WinSCP.Protocol]::ftp
    $sessionOptions.HostName = "host"
    $sessionOptions.PortNumber = "port"
    $sessionOptions.UserName = "user"
    $sessionOptions.Password = "pass"

    $session = New-Object WinSCP.Session

    try
    {
        # Connect
        $session.DisableVersionCheck = "true"
        $session.Open($sessionOptions)

        $localPath = "C:\users\user\desktop\file"
        $remotePath = "/"
        $fileName = "*.txt"
        $fileNamee = "*.log"
        $remotePath2 = "/completed"
        $directoryInfo = $session.ListDirectory($remotePath)
        $directoryInfo = $session.ListDirectory($remotePath2)

        # Download the file
        $session.GetFiles(($remotePath + $fileName), $localPath).Check()
        $session.GetFiles(($remotePath + $fileNamee), $localPath).Check()

        $session.MoveFile(($remotePath + $fileName, $remotePath2)).Check()
        $session.MoveFile(($remotePath + $fileNamee, $remotePath2)).Check() 

    }
    finally
    {
        # Disconnect, clean up
        $session.Dispose()
    }

    exit 0
}
catch [Exception]
{
    Write-Host $_.Exception.Message
    exit 1
}
powershell ftp winscp winscp-net
2个回答
1
投票

您的代码中有很多问题:


targetPath方法的Session.MoveFile自变量是将文件移动/重命名到的路径。

因此,如果您使用目标路径Session.MoveFile,则试图将文件移动到根文件夹并将其重命名为/complete。当您可能要将文件移动到文件夹complete并保留其名称时。为此,请使用目标路径/complete(或使其更明显的是/complete/)。

您当前的代码失败,因为您正在将文件重命名为已经存在的文件夹的名称。


您实际上在/complete/*中有相同的错误。您正在将所有文件(.GetFiles*.txt)都下载到文件夹*.log中,并将它们全部保存为相同的名称C:\users\user\desktop,彼此覆盖。


您在两个参数周围都使用了不正确的括号,而不是仅在第一个参数周围使用了括号。虽然我不是PowerShell专家,但实际上我是说您完全以这种方式省略了该方法的第二个参数。


此外,请注意file方法不返回任何内容(与MoveFile相反)。因此,没有对象可以调用GetFiles方法。


GetFiles(与.Check()相比,请注意单数形式)仅移动单个文件。因此,您不应使用文件掩码。实际上,当前的实现允许使用文件掩码,但是这种使用没有记录,在以后的版本中可能不推荐使用。

无论如何,最好的解决方案是迭代MoveFile返回的实际下载文件的列表,然后逐个移动文件。

这样可以避免出现竞争情况,即在其中下载文件集,添加新文件(未下载),并且将它们错误地移动到“完成”文件夹。


代码应该看起来像((仅对于第一组文件,即GetFiles):

GetFiles

[请注意,由于我不确定,*.txt的路径实际上是什么。


实际上有非常相似的示例代码:$remotePath2 = "/completed/" ... $transferResult = $session.GetFiles(($remotePath + $fileName), $localPath) $transferResult.Check() foreach ($transfer in $transferResult.Transfers) { $session.MoveFile($transfer.FileName, $remotePath2) }


0
投票

您是否已检查以确保您的进程有权将文件移动到新目录?

© www.soinside.com 2019 - 2024. All rights reserved.