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*.*

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;",
    $remotePath = "/path"
    # Load WinSCP .NET assembly
    Add-Type -Path "WinSCPnet.dll"
    # Setup session options
    $sessionOptions = New-Object WinSCP.SessionOptions
        # Connect
        Write-Host "Connecting..."
        $session = New-Object WinSCP.Session
        # Retrieve file list
        Write-Host "Listing..."
        $files = $session.EnumerateRemoteFiles($remotePath, "*", [WinSCP.EnumerationOptions]::None)
        Write-Host "Renaming..."
        $timestampPrefix = $(Get-Date -Format "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"
        # Disconnect, clean up
    exit 0
catch [Exception]
    Write-Host ("Error: {0}" -f $_.Exception.Message)
    exit 1
  library_example_advanced_rename.txt · Last modified: by martin

Search Documentation

This page


About donations

$9   $19   $49   $99

About donations



Site design by Black Gate