【发布时间】: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