Automate File Transfers with WinSCP Scripts

On this page

Quick answer. Put the commands in a UTF-8 text file, run them with winscp.com /ini=nul /log=... /script=..., and pass -hostkey with the fingerprint you already checked in the graphical window. Exit code 0 means the commands finished. Exit code 1 means you should read the log before you run the job again. Do not put the account password in the script, and do not replace the fingerprint with an asterisk.

What you need

  • A successful manual login, including a host key you have already verified. Scripting does not remove that requirement. It only lets you supply the expected fingerprint so the prompt does not block the job.
  • The path to WinSCP.com on this PC. The 32-bit installer usually places it under C:\Program Files (x86)\WinSCP\. A 64-bit build may use C:\Program Files\WinSCP\. Use the path that exists on your machine.
  • A private key the scheduled account can read, if you are not using an interactive password prompt. A prompt cannot appear when nobody is logged on.
Diagram of winscp.com running a script with a verified host key, a put or get command, and exit codes 0 and 1.
The host key stays in the open command. The log and the exit code tell you whether the copy happened.

The command line

winscp.com is the console tool. winscp.exe /console is another way into the same mode. For a job, prefer winscp.com and a script file. The script must be UTF-8 or UTF-16 with a byte order mark. Commands you type interactively still prompt the way the graphical program does. A script started with /script or /command runs in batch mode, and overwrite confirmations are off.

/ini=nul starts from default settings instead of the graphical configuration. That protects the job from a preference you changed later, such as a synchronization option, and it makes the script portable to another PC. The cost is that saved sites and cached host keys in your profile are not visible. Everything the job needs must be in the script, including the fingerprint.

/log writes a session log. Add /loglevel=0 for normal detail. Raise the level only while you are diagnosing quoting, because verbose logs are large and can contain paths you would not post publicly.

A basic upload script

Save this as C:\transfers\scripts\upload.txt. Replace the user, host, key path, fingerprint, and folders. The fingerprint is the SHA-256 value you copied from a connection you already verified. It looks like ssh-ed25519 255 SHA256: followed by the fingerprint body.

# Stop the job on the first failed command.
option batch abort
option confirm off

# Log in with a key. No password is stored in this file.
open sftp://[email protected]/ -privatekey="C:\keys\example.ppk" -hostkey="ssh-ed25519 255 SHA256:replace-with-verified-fingerprint"

lcd C:\transfers\outgoing
cd /home/example-user/incoming
put report-*.csv
exit

What each line does:

  • option batch abort stops the script when a command fails instead of continuing into the wrong folder.
  • option confirm off allows the script to overwrite files. In batch mode a confirmation would otherwise be answered “no,” and the overwrite would never happen. Point lcd and cd at the right directories so the overwrite is the file you intend.
  • open starts an SFTP session. -privatekey selects the .ppk file. -hostkey accepts only that fingerprint.
  • lcd changes the local directory. cd changes the remote directory. Both happen before put, so the mask cannot upload from whatever directory the scheduler happened to start in.
  • put report-*.csv uploads matching files from the local directory to the remote directory.
  • exit closes the session and ends the program.

Run it from Command Prompt:

"C:\Program Files (x86)\WinSCP\WinSCP.com" /ini=nul /log="C:\transfers\logs\upload.log" /script="C:\transfers\scripts\upload.txt"

Create the logs folder first. If the path to WinSCP.com is different, use that path. Quotes are required when a path contains spaces.

Download and the delete switch

get downloads. This example copies remote CSV files into a local folder and leaves the remote files in place:

option batch abort
option confirm off
open sftp://[email protected]/ -privatekey="C:\keys\example.ppk" -hostkey="ssh-ed25519 255 SHA256:replace-with-verified-fingerprint"
lcd C:\transfers\incoming
cd /home/example-user/outgoing
get *.csv
exit

get -delete removes the remote file after a successful download. That is useful for a pickup folder and destructive if the mask is wrong. Do not add -delete until the same get without it has placed the files you expect, and until you can restore those files from somewhere else. The WinSCP get command documentation describes the switch. Test it on a disposable filename, not on a production directory.

Synchronization in a script

synchronize remote makes the remote directory look like the local one for the files it compares. synchronize local updates the local directory from the server. Add a delete behavior only after you have read the command’s documentation and have a backup. A graphical preview, described in the transfer guide, is the safer first run. Timestamps that disagree between FTP and the PC can copy the same files forever. Prefer SFTP for scheduled sync when you have a choice.

option batch abort
option confirm off
open sftp://[email protected]/ -privatekey="C:\keys\example.ppk" -hostkey="ssh-ed25519 255 SHA256:replace-with-verified-fingerprint"
lcd C:\sites\example
cd /var/www/example
synchronize remote
exit

This sample does not include a delete switch. Files that exist only on the server stay there.

PowerShell and the .NET assembly

Scripting is enough when the job is a straight copy. When you need loops, per-file decisions, or richer error handling, the WinSCP .NET assembly is the documented tool. It is installed as WinSCPnet.dll beside the program. The assembly is licensed under the Mozilla Public License, separate from the GPL program. You use the DLL on the machine where WinSCP is installed. This site does not distribute it.

Add-Type -Path "C:\Program Files (x86)\WinSCP\WinSCPnet.dll"
$options = New-Object WinSCP.SessionOptions -Property @{
  Protocol = [WinSCP.Protocol]::Sftp
  HostName = "example.com"
  UserName = "example-user"
  SshPrivateKeyPath = "C:\keys\example.ppk"
  SshHostKeyFingerprint = "ssh-ed25519 255 SHA256:replace-with-verified-fingerprint"
}
$session = New-Object WinSCP.Session
try {
  $session.Open($options)
  $session.PutFiles("C:\transfers\outgoing\*.csv", "/home/example-user/incoming/").Check()
}
finally {
  $session.Dispose()
}

Session.Open fails if the fingerprint does not match, which is what you want. PutFiles followed by Check throws when a transfer fails, so the script does not continue as if the files had moved. There is a password property on the session options. Leave it out. A key is the better fit for an unattended job, and a password in a .ps1 file is readable by anyone who can read that file.

Task Scheduler

  1. Create a basic task

    Open Task Scheduler and create a task. The trigger is your schedule. The action is Start a program. Program/script is the full path to WinSCP.com. Add arguments:

    /ini=nul /log="C:\transfers\logs\upload.log" /script="C:\transfers\scripts\upload.txt"

    Set “Start in” to C:\transfers\scripts so any relative path you later add has a known base. Prefer the absolute paths already in the script.

  2. Choose the Windows account deliberately

    If the task runs only when you are logged on, Pageant can hold the key. If the task must run when you are logged off, Pageant is not available. Store a dedicated .ppk where only that Windows account can read it, and restrict the key on the server to the directory the job uses. A key that can log in as an administrator is the wrong key for a nightly CSV upload. The task will also need permission to read the script and write the log.

  3. Run it once by hand

    Use Run in Task Scheduler while you are watching. Then open the log. You want a completed put and exit code 0. Task Scheduler’s history should not be the only record. The WinSCP log shows the protocol error. History only shows that the process started.

Registry configuration is per Windows user. A task that runs as a different account cannot see host keys you accepted in your own graphical session. /ini=nul plus -hostkey avoids that trap. An INI file is the other documented approach. If several jobs run at once, do not point them at one writable INI. They can collide while saving it. /ini=nul avoids that too.

Logging and exit codes

WinSCP returns 0 when the commands finish and 1 when a command fails or a prompt is aborted. In a batch file, %ERRORLEVEL% holds that value after WinSCP.com returns. In Task Scheduler, a non-zero exit is the signal to open the log, not to click Run again blindly.

XML logging, with /xmllog, is the documented way to inspect results in more detail. Use it when a simple log is not enough to see which file failed. Keep logs on the PC that runs the job. Do not post a raw log into a public ticket. Logs contain host names, paths, and sometimes protocol details you did not mean to share. They should not contain your private key. If you ever used a session URL with a password in it, assume that password is in the log, revoke it, and remove it from the script.

When the script fails

  • Host key does not match. The server key changed or the fingerprint in the script is wrong. Do not switch to a wildcard. Re-check the fingerprint with the administrator, then update the script.
  • Authentication failed. The .ppk path is wrong for the task account, the public key is not in authorized_keys, or the passphrase cannot be entered. See authentication failed.
  • Cannot find the file. lcd or cd is wrong, or the mask does not match. Filenames are case-sensitive in WinSCP scripts even if a particular server is not.
  • The job works in your session and fails in the scheduler. The task account cannot read the key, the log directory, or the script. Grant those permissions instead of running the task as an interactive administrator every night.

The official scripting examples sometimes show a password inside a session URL so the syntax is visible. Do not copy that pattern into a file you save. Use a private key, and keep the passphrase off the command line.

FAQ

Can the site generate the script for me?

No. This page only shows the syntax. WinSCP itself can generate a script template from a saved site with Manage, Generate Session URL/Code. Remove any password that template includes before you store the file.

What does /ini=nul do?

It starts with no configuration file. Saved sites, cached host keys, and preference changes from the graphical program are ignored. The script has to be complete on its own.

Is a wildcard host key ever appropriate?

Not in the jobs described here. Accepting every host key disables the check that tells you the server is the one you verified. Get the fingerprint from a connection you checked, and pin that value.

Previous: SettingsNext: Troubleshooting

Sources