This is an old revision of the document!
Advanced files rename on SFTP/FTP server
Simple rename with operation mask
With WinSCP scripting, you can use an operation mask to do simple batch changes to file names like:
- changing an extension:
mv *.htm *.html
- adding a suffix:
mv *.html *-backup.html
- changing leading characters:
mv new*.* old*.*
Advertisement
Advanced rename with PowerShell
But for more advanced rename operations, you need to use your favorite scripting language language, like PowerShell, to generate a new name and use WinSCP .NET assembly for the actual rename (or generate a script file).
The following example prefixes all files in a specified directory with a timestamp in format YYYY-MM-DD-
.
param ( # Use Generate URL function to obtain a value for -sessionUrl parameter. $sessionUrl = "sftp://user:mypassword;fingerprint=ssh-rsa-xx-xx-xx@example.com/", $remotePath = "/path" ) try { # Load WinSCP .NET assembly Add-Type -Path "WinSCPnet.dll" # Setup session options $sessionOptions = New-Object WinSCP.SessionOptions $sessionOptions.ParseUrl($sessionUrl) try { # Connect Write-Host "Connecting..." $session = New-Object WinSCP.Session $session.Open($sessionOptions) # Retrieve file list Write-Host "Listing..." $files = $session.EnumerateRemoteFiles($remotePath, "*", [WinSCP.EnumerationOptions]::None) Write-Host "Renaming..." $timestampPrefix = $(Get-Date -f "yyyy-MM-dd") + "-" foreach ($fileInfo in $files) { $oldName = $fileInfo.Name $oldPath = $fileInfo.FullName $newName = ($timestampPrefix + $oldName) $newPath = $session.CombinePaths($remotePath, $newName) Write-Host ("{0} => {1}" -f $oldPath, $newPath) $session.MoveFile($oldPath, $newPath) } Write-Host "Done" } finally { # Disconnect, clean up $session.Dispose() } exit 0 } catch [Exception] { Write-Host ("Error: {0}" -f $_.Exception.Message) exit 1 }
Advertisement