PS-WinSCP is a powershell script for handling file transfers with WinSCP. It is an alternative to the built-in script commands in WinSCP.
It supports the protocols supported by WinSCP : SFTP / SCP² / S3 / FTP / FTPS / WebDAV² (²: SCP and WebDAV have not been tested with this script).
The intention of this script is to use WinSCP from a scheduler, which means:
- to automate a reccuring unattended upload or download action
- simplify the arguments used (attempt to...)
- use return codes indicating the success or failure of the operation
- secure passwords used for transfers
This script supports :
- Unique file / Multiple files / Folder tree (including subfolders) transfers
- Usage of wildcards
- Include and Exclude parameters at the same time
It has been tested on Windows OS only.
- WinSCP 5.x : Download WinSCP .NET Assembly / COM Libray
- PowerShell 5.1 (later version may be compatible but have not been tested)
- CredentialStore 1.1.7 : this PS module allows to store and use password securely. See install instructions on Powershell Gallery. More info on CredentialStore module on GitHub
To display the script syntax, run
Get-Help .\WinSCP.ps1
or, to display full help, with parameters description and examples :
Get-Help .\WinSCP.ps1 -full
The main script parameters are :
-WinscpPath <path>
- Path to the WINSCP .Net dll matching the installed .NET Framework version.-Command upload|download
- Operation to executes : upload or download-SessionURL <url>
- SessionURL are one string containing several or all information needed for remote site connection.
Examples :
-sessionURL "s3://s3.eu-west-1.amazonaws.com/my-test-bucket/"
-sessionURL "sftp://user:password@my.sftpserver.com/incoming/"
-LocalPath <path>
- Path to folder or to individual file (source or target according to-Command
parameter upload or download respectively)-CSEntryName <MyEntry>
- CredentialStore Entry Name to get the Login and Password securely. Set it first for the current profile withSet-CsEntry
The following arguments allows to specify remote site as an alternative to -sessionURL
(for compatibility reasons)
-Protocol
- Protocol to use for remote :sftp
,ftp
,s3
,scp
orwebdav
²-HostName
- Remote server hostname-PortNumber
- Remote server port number-RemotePath
- Path to remote folder or file-UserName
- Login for authentication on remote server.-SecurePassword
- Password as SecureString for authentication on remote server-DeleteSourceFile
- Add this switch if source file(s) should be deleted after successful transfer
The following arguments allow to include or exclude files from source path.
-Include
- Filename or wildcard expression to select files. Wildcard characters supported here are*
and?
only.
`*` Matches any number (including zero) of arbitrary characters. Eg: `*.doc`; `about*.html`
`?` Matches exactly one character.
Eg: `photo????.jpg`
To use an advanced syntax of file masks, use a -FileMask
argument.
Caution -FileMask
applies on -Include
filter. Both must be combined.
-Filemask
- FileMask is a powerfull but touchy option allowing to select or exclude files or folder to download or upload.
It needs-Include
value to specify a larger set of files. FileMask will then include or exclude files from this set.
It supports more complex patterns or wildcards:
*
Matches any number (including zero) of arbitrary characters. Eg:"*.doc"
Multiples pattern can also be specified. Eg, to include all .doc and .html files :*.doc;*.html
?
Matches exactly one arbitrary character.photo????.jpg
[abc]
Matches one character from the set.index_[abc].html
[a-z]
Matches one character from the range.index_[a-z].html
|
to exclude some pattern.
Eg: Include all .doc files except those beginning with~
*.doc|~*
Exclude sub-folders:
-FileMask "|*/"
Include all files from current directory but exclude subfolders:
`-FileMask "*|*/"`
Other file mask examples and features are documented on https://winscp.net/eng/docs/file_mask
-
-FilePermissions
- Permissions as octal value as string to applied to a remote file (used for uploads only and for SFTP and SCP protocols only). When not specified, keep default permissions.
Eg:-FilePermissions 777
: to give rwx permissions for everyone -
-TransferMode
-Ascii
orBinary
, orAutomatic
(=based on extension).Binary
is by default Using this option enables an "advanced" behaviour using FileMask (and Include) -
-PreserveTimestamp
- Add this switch to preserve timestamps on transfered files. $true by default -
-IgnoreHostAuthenticityCheck
- Add this switch if the remote host authenticity should not be checked. SshHostKeyFingerprint won't be checked for SSH / SFTP server. Server certificate won't be checked for FTPS / S3 / WebDAV server.
-
-SshHostKeyFingerprint
- String containing the remote SSH Public Key fingerprint.
Eg :-SshHostKeyFingerprint "ssh-rsa 2048 e0:a3:0f:1a:04:df:5a:cf:c9:81:84:4e:08:4c:9a:06"
-
-SshPrivateKeyPath
- Path to SSH/SFTP Private Key file (can be passphrase protected) -
-SecurePrivateKeyCSEntryName
- CredentialStore Entry Name to get the passphrase allowing to read and use the SSH/SFTP Private Key for authentication. Set it first for the current profile withSet-CsEntry
-
-FtpMode
- EnablePassive
orActive
FTP Transfer Mode
- FtpSecure - Enable
Explicit
orImplicit
FTP Secure Mode. UseNone
to use insecure FTP mode.
.\Winscp.ps1 -protocol sftp -Hostname remotehost.com -Port 2222 -User mylogin -pass <SecureString> -remotePath "/incoming" -localPath "C:\to_send" -Include "*" -FilePermissions "644"
.\Winscp.ps1 -WinscpPath "C:\Program Files (x86)\WinSCP\WinSCPnet.dll" -SessionURL "s3://s3.eu-west-1.amazonaws.com/s3-my-bucketname-001/incoming" -localPath "C:\To_upload" -Include "*.txt" -command "upload" -CsEntry "MyCSEntryName"
Upload C:\To_upload\myfile.tst to S3 Bucket
.\Winscp.ps1 -SessionURL "s3://s3.eu-west-1.amazonaws.com/s3-my-bucketname-001/incoming/" -LocalPath "C:\To_upload\myfile.tst" -command "upload" -CsEntry "mylogin"
Download *.txt files from remote bucket, including matching files in subfolders
.\Winscp.ps1 -SessionURL "s3://s3.eu-west-1.amazonaws.com/s3-my-bucketname-001/outgoing/" -LocalPath "C:\To_upload" -Include "*" -FileMask "*.txt" -command "download" -CsEntry "mylogin"
powershell.exe -ExecutionPolicy Bypass -File winscp.ps1 -winscpPath "C:\Program Files (x86)\WinSCP\WinSCPnet.dll" -localPath "C:\\" -remotePath "/somedirectory" -Include "files*.txt" -hostname "someftp.com" -port 822 -user "xman" -password "encrypted" -direction "download" -protocol "sftp" -serverFingerprint "ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx" -deleteSourceFile
Besides some Console output, Winscp1.ps1 does not generate any output object.
However, a return code is generated:
- rc = 0 : Operation is 100% successful (download or upload operation succeeded completely)
- rc = 1 : Operation failed partially or completely
- rc = 20 : Operation succeeded but no files were transferred
The script use CredentialStore powershell module to get password or login+password.
Install CredentialStore Module : See instructions on Powershell Gallery.
To create a new entry:
- Log in with the user session that will be used to launch the WinSCP script
- In a Powershell console, type
Set-CsEntry
- Enter a unique CredentialStore Entry Name (≠ of login)
- Enter the login name for the remote site
- Enter the password
To connect to a SFTP server, a keyfile secured by a passphrase can be used. The protected keyfile is in ppk format (this format is created with PuttyGen). WinSCP.ps1 script gets the passphrase from a CredentialStore entry.
To create this entry, proceed in the same way as for a login/password.
- Log in with the user session that will be used to launch the WinSCP script
- In a Powershell console, type
Set-CsEntry
- Enter a unique CredentialStore Entry Name (≠ of login)
- The login is no use in this case
- Enter the passphrase which will decrypts the key file.
SessionURL Syntax :
<protocol>:// [ <username> [ : <password> ] [ ; <advanced> ] @ ] <host> [ : <port> ] / [ <destination directory> / ]
² : WebDAV protocol this script hasn't been tested with WebDAV Protocol.