Renver
Renver

Reputation: 77

How to run a WinSCP from ps1 file

I have a .ps1 file with my script. In this script I have a line with:

Start-Process "C:\activatebatch.bat"

If i execute it directly with ps1 file, everything works well. But if I set up a Windows Scheduler with ps1 as executive, the bat file doesn't start. In that bat file I have a WinSCP which sends file to server.

How could I set it to start .bat from .ps1 stored in Windows Scheduler? Or how could I execute WinSCP directly from PowerShell code?

I need it to call for WinSCP to send a file into server - and the options are stored in batch file:

"C:\Program Files (x86)\WinSCP\WinSCP.exe" user:[email protected] /command ^
    "put C:\ss\file.txt /home/scripts/windows/" ^
    "exit"

Upvotes: 3

Views: 7363

Answers (1)

Martin Prikryl
Martin Prikryl

Reputation: 202272

If you have a working WinSCP command line in a batch file, you may need to do few changes to make it compatible with PowerShell:

  • Batch file use ^ (caret) to escape a new line. PowerShell uses ` (backtick). So replace your carets to backticks.
  • And you obviously need to escape any characters with a special meaning in PowerShell, particularly $ (dollar sign), ` (backtick) and inner double quotes.

In your simple script, only the first point matters, so the correct command is:

& "C:\Program Files (x86)\WinSCP\WinSCP.exe" user:[email protected] /command `
    "put C:\ss\file.txt /home/scripts/windows/" `
    "exit"

Though I'd further recommend you using winscp.com instead of winscp.exe and adding /log switch to enable session logging for debugging purposes.

Also opening a session using a command-line argument is deprecated. You should use open command (and better also specify a protocol prefix – sftp://?).

& "C:\Program Files (x86)\WinSCP\WinSCP.exe" /command `
    "open user:[email protected]" `
    "put C:\ss\file.txt /home/scripts/windows/" `
    "exit"

WinSCP 5.14 beta can actually generate a PowerShell – WinSCP command template for you.


Though for a better control, it's recommended to use WinSCP .NET assembly from PowerShell.

Upvotes: 2

Related Questions