Delete files on upload the files

Advertisement

mehdi.rahimi
Joined:
Posts:
1

Delete files on upload the files

I wrote a piece of code using variety of sample scripts available on the net and still have an issue deleting the files after they get uploaded on a remote location. Please help as Im meeting my deadlines... No matters where I put remove files, I always get Exception calling "RemoveFiles" with "1" argument(s): "Recursive calls not allowed"

      [Reflection.Assembly]::LoadFrom("C:\Program Files\WinSCP\WinSCPnet.dll") | Out-Null 
      
     # Session.FileTransferred event handler
 
function FileTransferred
{
    Param($e)
 
    if ($e.Error -eq $Null)
    {
        Write-Host ("Upload of {0} succeeded" -f $e.FileName)
       #If Download succeeded, remove the files from source
      
    }
    else
    {
        Write-Host ("Upload of {0} failed: {1}" -f $e.FileName, $e.Error)
    }
 
    if ($e.Chmod -ne $Null)
    {
        if ($e.Chmod.Error -eq $Null)
        {
            Write-Host ("Permisions of {0} set to {1}" -f $e.Chmod.FileName, $e.Chmod.FilePermissions)
        }
        else
        {
            Write-Host ("Setting permissions of {0} failed: {1}" -f $e.Chmod.FileName, $e.Chmod.Error)
        }
 
    }
    else
    {
        Write-Host ("Permissions of {0} kept with their defaults" -f $e.Destination)
    }
 
    if ($e.Touch -ne $Null)
    {
        if ($e.Touch.Error -eq $Null)
        {
            Write-Host ("Timestamp of {0} set to {1}" -f $e.Touch.FileName, $e.Touch.LastWriteTime)
        }
        else
        {
            Write-Host ("Setting timestamp of {0} failed: {1}" -f $e.Touch.FileName, $e.Touch.Error)
        }
 
    }
    else
    {
        # This should never happen with Session.SynchronizeDirectories
        Write-Host ("Timestamp of {0} kept with its default (current time)" -f $e.Destination)
    }
   foreach ($e in $synchronizationResult.uploads)
       {
             $removalResult = $session.RemoveFiles($session.EscapeFileMask($e.FileName))
 
                if ($removalResult.IsSuccess)
                {
                    Write-Host ("Removing of file {0} succeeded" -f
                        $e.FileName)
                }
                else
                {
                    Write-Host ("Removing of file {0} failed" -f
                        $e.FileName)
                }}
    
}

     # Main script
try
{
     $sessionOptions = New-Object WinSCP.SessionOptions 
      $sessionOptions.Protocol = [WinSCP.Protocol]::sftp 
      $sessionOptions.PortNumber = 9922 
      $sessionOptions.Timeout = "120" 
      $sessionOptions.HostName = "123456" 
      $sessionOptions.UserName = "123456" 
      $sessionOptions.Password = "123456"
     $sessionOptions.SshHostKeyFingerprint = "123456"

      $session = New-Object WinSCP.Session 
     
    try
    {
        $localPath = "C:\Users\rahimm\Desktop\TestSftpLocation\"
        $remotePath = "/Oresponces/"
   
      # Will continuously report progress of synchronization
        $session.add_FileTransferred( { FileTransferred($_) } )
 
        # Connect
        $session.Open($sessionOptions)
 
        # Synchronize files
        $synchronizationResult = $session.SynchronizeDirectories(
            [WinSCP.SynchronizationMode]::Remote, $localPath, $remotePath, $False)
         
         
 
        # Throw on any error
        $synchronizationResult.Check()
    }
    finally
    {
        # Disconnect, clean up
        $session.Dispose()
    }
 
    exit 0
}
catch [Exception]
{
    Write-Host $_.Exception.Message
    exit 1
}

Reply with quote

Advertisement

martin
Site Admin
martin avatar
Joined:
Posts:
41,517
Location:
Prague, Czechia

Re: Delete files on upload the files

You cannot call back into Session from event handlers.

Moreover your code does not make sense. You should move your foreach ($e in $synchronizationResult.uploads) loop to main block after $session.SynchronizeDirectories finishes.

Reply with quote

nealobrien
Joined:
Posts:
6

sync with bidirectional delete or move file

I need the same feature as noted by the op:

1. sync that mirrors all file movements and deletes (on both local or remote) - this greatly preferred
2. a command or succinct script to move files to the server (but not copy, ie put or get)

Does this exist or are there plans to support it?

Many thanks

Reply with quote

martin
Site Admin
martin avatar
Joined:
Posts:
41,517
Location:
Prague, Czechia

Re: sync with bidirectional delete or move file

nealobrien wrote:

1. sync that mirrors all file movements and deletes (on both local or remote) - this greatly preferred
WinSCP does not keep any data about previous state of the folders. Without that:
- If file is existing one side, but missing on the other, how do you tell if it was added on one side or deleted on the other?
- If new file is present on one side and another file is absent, how do you tell if it was rename or simply new file added and another removed?

2. a command or succinct script to move files to the server (but not copy, ie put or get)
I do not understand. Please elaborate.

Reply with quote

nealobrien
Joined:
Posts:
6

We need "synchronise both" to also delete in both directions. Or, for synchronise local to also delete local when remote is moved/deleted & conversely for synchronise remote to also delete remote when local file is moved/deleted. Im pretty sure Winscp could do this, but as this feature seems not to be offered yet, is there a recommendation on the simplest solution?

The reason we need this is because files are produced one machine yet are consumed (processed) on the other server, and it happens in both directions. Its basically messaging with files.

Reply with quote

Advertisement

martin
Site Admin
martin avatar
Joined:
Posts:
41,517
Location:
Prague, Czechia

nealobrien wrote:

We need "synchronise both" to also delete in both directions.
I understand. I asked you how do you image this could be implemented.

Or, for synchronise local to also delete local when remote is moved/deleted & conversely for synchronise remote to also delete remote when local file is moved/deleted.
That's what -delete switch does.
https://winscp.net/eng/docs/scriptcommand_synchronize

Reply with quote

nealobrien
Joined:
Posts:
6

If I read your second answer correctly, "That's what -delete switch does.", then we're okay. But I thought -delete will delete from target only when a file is deleted in source, no?

As to the first note, winscp could implement this by polling both directories and when a file appears in one it copies it to the other, and when a file is deleted in one it deletes in the other. As long as state is maintained by winscp this seems possible:

1. Upon start synchronise, then load a hash of both local and remote
2. Every x seconds, poll local and remote, and load file list to a tmp_hash (really one for each directory)
3. For both local and remote, for each directory, compare tmp_hash with orig_hash
for each new file in tmp_hash
add to the other
for each missing file in tmp_hash
delete from the other

set orig_hash = tmp_hash

Reply with quote

martin
Site Admin
martin avatar
Joined:
Posts:
41,517
Location:
Prague, Czechia

nealobrien wrote:

But I thought -delete will delete from target only when a file is deleted in source, no?
It deletes file from target when it does not exist in source (no matter if it ever existed there or not).

As to the first note, winscp could implement this by polling both directories and when a file appears in one it copies it to the other, and when a file is deleted in one it deletes in the other. As long as state is maintained by winscp this seems possible:
...
Of course. But that's a completely different function that what we have atm.

Reply with quote

Advertisement

You can post new topics in this forum