This is an old revision of the document!

Using WinSCP .NET Assembly from PowerShell

Advertisement

About PowerShell

Windows PowerShell is Microsoft’s task automation framework, consisting of a command-line shell and associated scripting language built on .NET Framework.

PowerShell is built into Windows 7 and newer; and is optionally available for Windows 98 SP2 and newer.1

PowerShell scripts can be directly executed, they do not need to be compiled first.

PowerShell Scripting

From WinSCP scripting perspective, important aspect of PowerShell (powershell.exe) is its ability to run simple, yet powerful, scripts that can make use functionality exposed by WinSCP .NET assembly.

The powershell.exe is located in %WINDIR%\System32\WindowsPowershell\v1.02. Typically you run powershell.exe with -File argument followed by path to your PowerShell script. The script file needs to have .ps1 extension:

powershell.exe -File upload.ps1

Note that by default, executing PowerShell scripts is disabled. To override that, you can either lift the restriction by typing using Set-ExecutionPolicy cmdlet on PowerShell administrator console3:

Set-ExecutionPolicy Unrestricted

or use -ExecutionPolicy argument for every script run:

powershell.exe -ExecutionPolicy Unrestricted -File upload.ps1 

Advertisement

Installing the Assembly

First, you need to install the WinSCP .NET assembly.4

Using from PowerShell

You use WinSCP .NET assembly from PowerShell as any other .NET assembly.

Though there are some less known techniques and peculiarities that you may need to use, which are described in following sections.

Loading Assembly

PowerShell script needs to load the assembly before it can use classes the assembly exposes. To load assembly use method System.Reflection.Assembly.LoadFrom. You may want to redirect diagnostic output of the method to Out-Null.

[Reflection.Assembly]::LoadFrom("WinSCPnet.dll") | Out-Null

(Use winscp.dll for the releases before the latest beta version.)

Accessing Enumeration Values

Enumeration values are accessed using static field syntax [[Namespace.Type]]::Member, for example [WinSCP.Protocol]::Sftp.

Event Handlers

The Session class exposes several events.

If you need to make use of these events:

  • Define event handling function;
  • Associate the event handling function with an instance of Session class using Register-ObjectEvent cmdlet.

See following code snippet:

# Event handling function
function FileTransferred
{
    Param($e)
 
    if ($e.Error -eq $Null)
    {
        Write-Host ("Transfer of {0} succeeded" -f $e.FileName)
    }
    else
    {
        Write-Host ("Transfer of {0} failed: {1}" -f $e.FileName, $e.Error)
    }
}
 
...
 
# Subscribe to the event
Register-ObjectEvent -inputObject $session -eventName FileTransferred `
    -Action { FileTransferred($event.sourceEventArgs) } | Out-Null

Advertisement

Alternatively, you can make use of Session.add_Event method, where Event is a name of the event:

# Subscribe to the event
$session.add_FileTransferred( { FileTransferred($_) } )

Example

This example is functionally equivalent to overall C# example for WinSCP .NET assembly.

There are also other PowerShell examples.

try
{
    # Load WinSCP .NET assembly
    # Use "winscp.dll" for the releases before the latest beta version.
    [Reflection.Assembly]::LoadFrom("WinSCPnet.dll") | Out-Null
 
    # Setup session options
    $sessionOptions = New-Object WinSCP.SessionOptions
    $sessionOptions.Protocol = [WinSCP.Protocol]::Sftp
    $sessionOptions.HostName = "example.com"
    $sessionOptions.UserName = "user"
    $sessionOptions.Password = "mypassword"
    $sessionOptions.SshHostKeyFingerprint = "ssh-rsa 1024 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"
 
    $session = New-Object WinSCP.Session
 
    try
    {
        # Connect
        $session.Open($sessionOptions)
 
        # Upload files
        $transferOptions = New-Object WinSCP.TransferOptions
        $transferOptions.TransferMode = [WinSCP.TransferMode]::Binary
 
        $transferResult = $session.PutFiles("b:\toupload\*", "/home/user/", $False, $transferOptions)
 
        # Throw on any error
        $transferResult.Check()
 
        # Print results
        foreach ($transfer in $transferResult.Transfers)
        {
            Write-Host ("Upload of {0} succeeded" -f $transfer.FileName)
        }
    }
    finally
    {
        # Disconnect, clean up
        $session.Dispose()
    }
 
    exit 0
}
catch [Exception]
{
    Write-Host $_.Exception.Message
    exit 1
}

Advertisement

Converting Script to PowerShell Code

When you are considering converting your script to code that uses WinSCP .NET assembly, PowerShell, thanks to its ubiquity, can be a good choice, particularly, when you do not have your own preferred language that supports .NET.

  1. The text is copy from Wikipedia PowerShell article.Back
  2. It’s v1.0, disregarding what version you actually use.Back
  3. Run powershell.exe as Administrator to get PowerShell consoleBack
  4. You do not need to register the assembly for COM, as PowerShell can use .NET assemblies directly.Back

Last modified: by martin