我有一個很的基本功能,所以同步一個遠程文件夾到本地。這與FileTransferred
處理程序配合良好,我想將FileTransferProgress
添加到組合中,然後使用Write-Progress
。但是我無法理解,因爲在會話打開時,我無法添加FileTransferProgress
處理程序。爲什麼在會話打開時不能添加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
處理程序?
我想通了。我很欣賞信息和文檔更新。我從來沒有想過添加一個標誌,以便可以工作 – Matt