Watch for changes in local folder and upload them to SFTP server
Just take the path to the new file and use RemotePath.TranslateLocalPathToRemote
to map it to a server path, and upload the file there.
The code will be a lot simpler. All you need to do is to make sure new folders are re-created on the server.
# Watches a directory for new files and fires off the batch file to push to connection$remotePath = "/data"$localPath = "C:\pathTo\watchfolder"$watcher = New-Object System.IO.FileSystemWatcher$watcher.Path = $localPath$watcher.Filter = "*.csv"$watcher.IncludeSubdirectories = $True$watcher.EnableRaisingEvents = $True### LISTEN FOR CREATERegister-ObjectEvent $watcher Created -SourceIdentifier FileCreated -Action { try { $localFilePath = $event.SourceEventArgs.FullPath Write-Host "Local path: $localFilePath" $assemblyPath = "C:\Program Files (x86)\WinSCP" Add-Type -Path (Join-Path $assemblyPath "WinSCPnet.dll") # Setup session options $sessionOptions = New-Object WinSCP.SessionOptions -Property @{ Protocol = [WinSCP.Protocol]::Sftp HostName = "example.com" UserName = "username" Password = "password" SshHostKeyFingerprint = "ssh-rsa 2048 xxxxxxxxxxx...=" } $session = New-Object WinSCP.Session try { $remoteFilePath = [WinSCP.RemotePath]::TranslateLocalPathToRemote( $localFilePath, $localPath, $remotePath) Write-Host "Remote path: $remoteFilePath" # Connect $session.Open($sessionOptions) # Check if corresponding remote directory exists, if not, create it $i = $remoteFilePath.LastIndexOf("/") $remoteDirPath = $remoteFilePath.SubString(0, $i) if (($remoteDirPath.Length -gt 0) -and !$session.FileExists($remoteDirPath)) { Write-Host "New subdirectory, creating $remoteDirPath on server" $session.CreateDirectory($remoteDirPath) } $session.PutFiles($localFilePath, $remoteFilePath).Check() Write-Host "Upload of $localFilePath succeeded" } finally { # Disconnect, clean up $session.Dispose() } } #end of first try catch { Write-Host "Error: $($_.Exception.Message)" }} #end of actionwhile ($True) { sleep 5 }