What I want to achieve is to watch multiple local folders and whenever there is a file added to one of these folders I want that it must synchronise/copy those folders to the remote directory that is specified. If I execute my code nothing happens.
This is what I tried in Powershell:
# Set variables for local paths and remote path
$remotePath = "/myRemotePath/here/"
$localPaths = @(
"D:localmyfirstlocalfolder",
"D:localmysecondlocalfolder"
)
# Initialize an array to hold watchers
$global:watchers = @()
# Function to handle the file created event
function HandleFileCreated {
param(
[string]$localFilePath
)
Write-Host "File created: $localFilePath"
# Specify WinSCP assembly path
$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 = "hostname.eu"
UserName = "username"
Password = "password"
SshHostKeyFingerprint = "ssh-rsa 2048 xxxx..."
}
$session = New-Object WinSCP.Session
try {
# Get the local path from the event args
$localPath = Split-Path -Path $localFilePath
# Calculate remote file path based on original local path and remote base path
$relativePath = $localFilePath.Substring($localPath.Length + 1)
$remoteFilePath = $remotePath + $relativePath.Replace("", "/")
Write-Host "Remote path: $remoteFilePath"
# Connect to the SFTP server
$session.Open($sessionOptions)
# Upload the file to the remote path
$transferResult = $session.PutFiles($localFilePath, $remoteFilePath)
$transferResult.Check()
Write-Host "Upload of $localFilePath succeeded"
}
catch {
Write-Host "Error: $($_.Exception.Message)"
}
finally {
# Disconnect and dispose the session
$session.Dispose()
}
}
# Loop through each local path and create a FileSystemWatcher
foreach ($localPath in $localPaths) {
$watcher = New-Object System.IO.FileSystemWatcher
$watcher.Path = $localPath
$watcher.Filter = "*.*"
$watcher.IncludeSubdirectories = $false # Adjust based on your needs
$watcher.EnableRaisingEvents = $true
# Generate a unique event identifier based on the local path
$watcherEventName = "FileCreated_" + [System.Guid]::NewGuid().ToString()
# Register the event handler for file creation
Register-ObjectEvent $watcher Created -SourceIdentifier $watcherEventName -Action {
$eventArgs = $EventArgs[1]
$localFilePath = $eventArgs.FullPath
HandleFileCreated -localFilePath $localFilePath
}
# Add watcher to the global watchers array
$global:watchers += $watcher
}
# Keep the script running indefinitely
while ($true) {
Start-Sleep -Seconds 5
}
Any help would be appreciated 🙂