【问题标题】:Why can I not add a FileTransferProgress handler while the session is open?为什么我不能在会话打开时添加 FileTransferProgress 处理程序?
【发布时间】:2017-06-02 15:39:50
【问题描述】:

我有一个 非常 基本功能,所以将远程文件夹同步到本地。这与FileTransferred 处理程序配合得很好,我想将FileTransferProgress 添加到组合中,然后使用Write-Progress。但是我无法做到这一点,因为在会话打开时我似乎无法添加 FileTransferProgress 处理程序。

function Sync-RemoteToLocalFolder{
    [CmdletBinding()]
    param(
        [Parameter(Mandatory=$true)]
        [WinSCP.Session]$Session,

        [Parameter(Position=0)]
        [string]$RemotePath="/",

        [Parameter(Position=1,mandatory)]
        [string]$LocalPath
    )

    $fileTransferedEvent = {Invoke-FileTransferredEvent $_}

    # Determine how many files are in this folder tree
    $fileCount = (Get-WinSCPItems -Session $Session -RemotePath $RemotePath | Where-Object{$_.IsDirectory -eq $false}).Count

    $fileProgressEvent = {Invoke-FileProgressEvent $_ $fileCount}

    try{
        # Set the file transfer event handler
        Write-Verbose "Setting Transfered handler"
        $session.add_FileTransferred($fileTransferedEvent)

        # Set the transfer progress handler
        Write-Verbose "Setting Progress handler"
        $Session.add_FileTransferProgress($fileProgressEvent)

        # Sync the directories
        Write-Verbose "Syncronizing '$LocalPath' with '$RemotePath'"
        $synchronizationResult = $session.SynchronizeDirectories([WinSCP.SynchronizationMode]::Local, $LocalPath, $RemotePath, $False)

        # Check the result for errors
        $synchronizationResult.Check()

        # Remove the handlers from the session
        $session.remove_FileTransferred($fileTransferedEvent)
        $Session.remove_FileTransferProgress($fileProgressEvent)

    }catch [Exception]{
        Write-Error $_
    }
}

如果我运行它,并通过了一个打开的$session,那么我会收到消息Sync-RemoteToLocalFolder : Session is already opened。我发现这很奇怪,因为我动态添加了一种不同类型的处理程序,但它们的功能可能不同。所以我可以注释掉关于FileTransferProgress 的两行,上面的函数可以按照我的意愿工作(有一些逻辑缺陷,但它们存在于这个问题之外,例如我需要更新$fileProgressEvent 的脚本块) .

为什么我不能在会话打开时添加FileTransferProgress 处理程序?

【问题讨论】:

    标签: powershell winscp powershell-5.0 winscp-net


    【解决方案1】:

    这是实现的限制。

    对此你无能为力。


    我是documented now:

    在调用Open之前必须订阅该事件。


    作为一种解决方法,您可以在事件处理程序中引入一个标志,以将其关闭。

    【讨论】:

    • 我想通了。我感谢信息和文档更新。我从没想过添加一个标志,这样就可以了
    猜你喜欢
    • 2021-05-16
    • 1970-01-01
    • 1970-01-01
    • 2023-03-10
    • 1970-01-01
    • 1970-01-01
    • 2015-08-23
    • 2014-04-25
    相关资源
    最近更新 更多