I’m writing a Powershell script using WinSCP where I want to synchronize all files that are put into a local folder (or folders) and whenever this happens it should be transfered/copied to a sftp server, remote directory.
I tried the following but this only detects it but doesn’t copy it to the sftp server directory. Thank you in advance for the help.
# Parameters for local and remote directories
$localFolder = "D:SOMETHINGREG"
$remoteFolder = "/LOCATION/SENT/"
# WinSCP executable path (adjust as necessary)
$winscpPath = "C:Program Files (x86)WinSCPWinSCP.com"
# SFTP connection details
$sftpHost = "sftp.eservices.something.eu"
$sftpUsername = "USER"
$sftpPassword = "password"
$sftpSessionName = "SFTP_Session"
# Function to synchronize files using WinSCP
function Synchronize-WithWinSCP {
param (
[string]$localPath,
[string]$remoteFolder
)
Write-Host "Connecting to SFTP server ($sftpHost)..."
$scriptBlock = {
param($winscpPath, $sftpUsername, $sftpPassword, $sftpHost, $sftpSessionName, $localPath, $remoteFolder)
& "$winscpPath" `
/log="winscp.log" `
/command `
"open sftp://${sftpUsername}:${sftpPassword}@${sftpHost} -sessionname ${sftpSessionName}" `
"lcd `"$localPath`"" `
"cd `"$remoteFolder`"" `
"put `"$localPath`"" `
"exit"
}
Start-Process powershell.exe -ArgumentList "-NoProfile -ExecutionPolicy Bypass -Command & { $scriptBlock }" -PassThru
}
# Monitor folder for file creations
$folderWatcher = New-Object System.IO.FileSystemWatcher
$folderWatcher.Path = $localFolder
$folderWatcher.IncludeSubdirectories = $false
$folderWatcher.EnableRaisingEvents = $true
# Define the event action when a new file is created
$onCreated = Register-ObjectEvent -InputObject $folderWatcher -EventName Created -Action {
$path = $Event.SourceEventArgs.FullPath
$name = $Event.SourceEventArgs.Name
Write-Host "File created: $name"
# Synchronize the new file to remote directory
Synchronize-WithWinSCP -localPath $path -remoteFolder $remoteFolder
}
# Function to stop monitoring and clean up
function Stop-FolderWatcher {
$folderWatcher.EnableRaisingEvents = $false
Unregister-Event -SourceIdentifier $onCreated.Name
}
Write-Host "Monitoring folder '$localFolder' for file additions..."
Write-Host "Press Ctrl+C to exit."
# Keep the script running until interrupted
try {
while ($true) {
Start-Sleep -Seconds 5 # Check every 5 seconds
}
}
finally {
Stop-FolderWatcher
}