Reputation: 46710
I have a very basic function so sync a remote folder to local. This is working well with a FileTransferred
handler and I wanted to add a FileTransferProgress
to the mix and then use Write-Progress
. However I cannot get to that since it appears I cannot add a FileTransferProgress
handler while the session is open.
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 $_
}
}
If I run this, with an open $session
passed then I get the message Sync-RemoteToLocalFolder : Session is already opened
. I found that odd since I added a different kind of handler on the fly but these could function differently. So I can comment out the two lines about the FileTransferProgress
and the above function works as much as I want it to (there are some logic flaws but they exist outside of this issue e.g. I need to update the scriptblock for $fileProgressEvent
).
Why can I not add a FileTransferProgress
handler while the session is open?
Upvotes: 1
Views: 304
Reputation: 202282
It's a limitation of the implementation.
Nothing you can do about it.
It's documented now:
The event has to be subscribed before calling
Open
.
As a workaround, you can introduce a flag in the event handler, to turn it off.
Upvotes: 2