使用WinSCP将文件移动到本地路径

huangapple go评论54阅读模式
英文:

Using WinSCP to move files to a local path

问题

我目前正在使用WinSCP在远程路径和本地路径之间同步文件到桌面电脑。我想要更改这样的操作,以便执行以下之一:

  1. 将文件从远程路径移动到本地路径
  2. 将文件从远程路径复制到本地路径,然后只删除已下载到本地路径的文件 - 在远程服务器上。

这是否可行?

以下是我的当前脚本,非常感谢任何帮助。

@echo on
cls
:SetFileLogVariables
SET localdir=C:\Users\User1\Received
SET remotedir=\folder_1
SET logfile=C:\Users\Users1\Logs\Syncanddelete.log

:SetPrgVariables
SET prgwinscp=C:\Users\Users1\AppData\Local\Programs\WinSCP\WinSCP.com
SET winscplogin="SyncandDelete"
SET winscpfile=%temp%\~tmpWinSCPFTPSyncT_%~N0.txt
IF EXIST "%winscpfile%" DEL /Q /F "%winscpfile%"

:SetWinSCPSyncCommand
REM 同步命令:
https://winscp.net/eng/docs/scriptcommand_synchronize
SET ftpcmd=synchronize local -delete -mirror "%localdir%\"

:ftpout
>>"%logfile%" ECHO.
>>"%logfile%" ECHO *************************** FTP OUT ***************************
>>"%logfile%" ECHO Synchronizing files to %winscplogin% server on %date% at %time%

>>"%winscpfile%" ECHO option batch on
>>"%winscpfile%" ECHO option confirm off
>>"%winscpfile%" ECHO option transfer binary
>>"%winscpfile%" ECHO open %winscplogin%
>>"%winscpfile%" ECHO cd "%remotedir%"
>>"%winscpfile%" ECHO %ftpcmd%
>>"%winscpfile%" ECHO close
>>"%winscpfile%" ECHO exit

>>"%logfile%" ECHO %winscpfile%
TYPE "%winscpfile%" >> %logfile%
>>"%logfile%" ECHO ------------------------------------------
"%prgwinscp%" /script="%winscpfile%" >>"%logfile%" 2>&1
>>"%logfile%" ECHO ------------------------------------------
IF EXIST "%winscpfile%" DEL /Q /F "%winscpfile%"
>>"%logfile%" ECHO Transmission complete on %date% at %time%

ping -n 2 -w 1000 127.0.0.1 > nul

请注意,这是您提供的脚本的翻译部分。如果您需要进一步的解释或帮助,请告诉我。

英文:

I am currently using WinSCP to synchronize files between a remote path and a local path to a desktop computer. I would like to change this so that either of the following occurs:

  1. Move files from the remote path to the local path
  2. Copy files from the remote path to the local path, then delete only the files that were
    downloaded to the local path - on the remote server.

Is this possible?

Here is my current script, any assistance is very much appreciated.

@echo on
cls
:SetFileLogVariables
SET localdir=C:\Users\User1\Received
SET remotedir=\folder_1
SET logfile=C:\Users\Users1\Logs\Syncanddelete.log

:SetPrgVariables
SET 
prgwinscp=C:\Users\Users1\AppData\Local\Programs\WinSCP\WinSCP.com
SET winscplogin="SyncandDelete"
SET winscpfile=%temp%\~tmpWinSCPFTPSyncT_%~N0.txt
IF EXIST "%winscpfile%" DEL /Q /F "%winscpfile%"

:SetWinSCPSyncCommand
REM synchronize command: 
https://winscp.net/eng/docs/scriptcommand_synchronize
SET ftpcmd=synchronize local -delete -mirror "%localdir%\"
   
:ftpout
>>"%logfile%" ECHO.
>>"%logfile%" ECHO ***************************  FTP OUT  
***************************
     >>"%logfile%" ECHO Synchronizing files to %winscplogin% 
server  on 
%date% at %time%

>>"%winscpfile%" ECHO option batch on
>>"%winscpfile%" ECHO option confirm off
>>"%winscpfile%" ECHO option transfer binary
>>"%winscpfile%" ECHO open %winscplogin%
>>"%winscpfile%" ECHO cd "%remotedir%"
>>"%winscpfile%" ECHO %ftpcmd%
>>"%winscpfile%" ECHO close
>>"%winscpfile%" ECHO exit

>>"%logfile%" ECHO %winscpfile%                                
TYPE "%winscpfile%" >> %logfile%
>>"%logfile%" ECHO ------------------------------------------ 
"%prgwinscp%" /script="%winscpfile%" >>"%logfile%" 2>&1
>>"%logfile%" ECHO ------------------------------------------
IF EXIST "%winscpfile%" DEL /Q /F "%winscpfile%"
>>"%logfile%" ECHO Transmission complete on %date% at %time%

ping -n 2 -w 1000 127.0.0.1 > nul

答案1

得分: 1

以下是翻译好的部分:

"While the code in your self-answer (copied verbatim from WinSCP website) solves the problem, it's imo overkill for most purposes."
"尽管你自己的答案中的代码(从WinSCP网站复制而来)解决了问题,但对于大多数情况来说,这是一种过度的解决方法。"

"See:"
"请参阅:"

"Once you have a working WinSCP script, you can easily achieve moving remote files to local folder using -delete switch of the get command:"
"一旦你拥有一个可用的WinSCP脚本,你可以轻松地使用[get命令的-delete开关将远程文件移动到本地文件夹:"

get -delete /source/remote/path/* C:\target\local\path\

"And If you choose to use PowerShell, you can simply call Session.GetFilesToDirectory with remove parameter set to true:"
"如果你选择使用PowerShell,你可以简单地调用Session.GetFilesToDirectory,并将remove参数设置为true:"

$session.GetFilesToDirectory($remotePath, $localPath, $null, $true).Check()

"The above line replaces about 40 lines of your code."
"上述代码行替代了大约40行你的代码。"

英文:

While the code in your self-answer (copied verbatim from WinSCP website) solves the problem, it's imo overkill for most purposes.

See:


Once you have a working WinSCP script, you can easily achieve moving remote files to local folder using -delete switch of the get command:

get -delete /source/remote/path/* C:\target\local\path\

And If you choose to use PowerShell, you can simply call Session.GetFilesToDirectory with remove parameter set to true:

<!-- language: lang-powershell -->

$session.GetFilesToDirectory($remotePath, $localPath, $null, $true).Check()

The above line replaces about 40 lines of your code.

答案2

得分: 0

以下是您提供的代码的中文翻译部分:

param (
    $localPath = "C:\Users\Users1\Folder1",
    $remotePath = "/foldersource/"
)

try
{
    # 加载 WinSCP .NET 程序集
    Add-Type -Path "WinSCPnet.dll"

    # 设置会话选项
    $sessionOptions = New-Object WinSCP.SessionOptions -Property 
    @{
        Protocol = [WinSCP.Protocol]::Sftp
        HostName = "*****"
        UserName = "*****"
        Password = "*****"
        SshHostKeyFingerprint = "ssh-rsa ********************"
        PortNumber = "****"
    }

    $session = New-Object WinSCP.Session

    try
    {
        # 连接
        $session.Open($sessionOptions)

        # 同步文件到本地目录,收集结果
        $synchronizationResult = $session.SynchronizeDirectories(
            [WinSCP.SynchronizationMode]::Local, $localPath, 
            $remotePath, $False)

        # 故意不调用 $synchronizationResult.Check
        # 因为它会在任何错误时中止我们的脚本。

        # 遍历每个下载
        foreach ($download in $synchronizationResult.Downloads)
        {
            # 成功或错误?
            if ($download.Error -eq $Null)
            {
                Write-Host "下载文件 $($download.FileName) 成功,从源文件中删除"
                # 下载成功,从源文件中删除文件
                $filename = [WinSCP.RemotePath]::EscapeFileMask($download.FileName)
                $removalResult = $session.RemoveFiles($filename)

                if ($removalResult.IsSuccess)
                {
                    Write-Host "删除文件 $($download.FileName) 成功"
                }
                else
                {
                    Write-Host "删除文件 $($download.FileName) 失败"
                }
            }
            else
            {
                Write-Host ("下载文件 $($download.FileName) 失败: $($download.Error.Message)")
            }
        }
    }
    finally
    {
        # 断开连接,清理
        $session.Dispose()
    }

    exit 0
}
catch
{
    Write-Host "错误: $($_.Exception.Message)"
    exit 1
}

以上是您提供的 PowerShell 脚本的中文翻译。如有任何疑问,请随时提出。

英文:

Based on https://winscp.net/eng/docs/library_example_delete_after_successful_download

<!-- language: lang-powershell -->

param (
    $localPath = &quot;C:\Users\Users1\Folder1&quot;,
    $remotePath = &quot;/foldersource/&quot;
)
  
try
{
    # Load WinSCP .NET assembly
    Add-Type -Path &quot;WinSCPnet.dll&quot;
 
    # Setup session options
    $sessionOptions = New-Object WinSCP.SessionOptions -Property 
    @{
        Protocol = [WinSCP.Protocol]::Sftp
        HostName = &quot;*****&quot;
        UserName = &quot;*****&quot;
        Password = &quot;*****&quot;
        SshHostKeyFingerprint = &quot;ssh-rsa ********************&quot;
        PortNumber = &quot;****&quot;
    }
 
    $session = New-Object WinSCP.Session
 
    try
    {
        # Connect
        $session.Open($sessionOptions)
 
        # Synchronize files to local directory, collect results
        $synchronizationResult = $session.SynchronizeDirectories(
            [WinSCP.SynchronizationMode]::Local, $localPath, 
            $remotePath, $False)
 
        # Deliberately not calling $synchronizationResult.Check
        # as that would abort our script on any error.
 
        # Iterate over every download
        foreach ($download in $synchronizationResult.Downloads)
        {
            # Success or error?
            if ($download.Error -eq $Null)
            {
                Write-Host &quot;Download of $($download.FileName) succeeded, removing from source&quot;
                # Download succeeded, remove file from source
                $filename = 
                    [WinSCP.RemotePath]::EscapeFileMask($download.FileName)
                $removalResult = $session.RemoveFiles($filename)

                if ($removalResult.IsSuccess)
                {
                    Write-Host &quot;Removing of file $($download.FileName) succeeded&quot;
                }
                else
                {
                    Write-Host &quot;Removing of file $($download.FileName) failed&quot;
                }
            }
            else
            {
                Write-Host (
                    &quot;Download of $($download.FileName) failed: $($download.Error.Message)&quot;)
            }
        }
    }
    finally
    {
        # Disconnect, clean up
        $session.Dispose()
    }

    exit 0
}
catch
{
    Write-Host &quot;Error: $($_.Exception.Message)&quot;
    exit 1
}

huangapple
  • 本文由 发表于 2023年2月23日 22:36:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/75546271.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定