This is an old revision of the document!

Download remote file from a path stored in clipboard

The following example uses WinSCP .NET assembly from a PowerShell script. If you have another preferred language, you can easily translate it.

The script downloads a file or directory pointed to by a path in clipboard to a local directory.

In the latest beta version, you can install this script as a WinSCP extension by using this page URL in the Add Extension command. The extension will automatically use the current local working directory as a target.

Advertisement

# @name         &Download from Path in &Clipboard
# @command      powershell.exe -ExecutionPolicy Bypass -File "%EXTENSION_PATH%" -sessionUrl "!S" -localPath "!\" %Pause% -sessionLogPath "%SessionLogPath%"
# @description  Downloads remote file from a path stored in clipboard to the current local directory
# @version      2
# @homepage     https://winscp.net/eng/docs/library_example_download_clipboard
# @require      WinSCP 5.8.3
# @option       Pause checkbox "&Pause at the end" -pause -pause
# @option       SessionLogPath file "&Session log file:"
# @optionspage  https://winscp.net/eng/docs/library_example_download_clipboard#options
 
param (
    # Use Generate URL function to obtain a value for -sessionUrl parameter.
    $sessionUrl = "sftp://user:mypassword;fingerprint=ssh-rsa-xx-xx-xx@example.com/",
    [Parameter(Mandatory)]
    $localPath,
    $sessionLogPath = $Null,
    [Switch]
    $pause = $False
)
 
try
{
    # Load WinSCP .NET assembly
    $assemblyPath = if ($env:WINSCP_PATH) { $env:WINSCP_PATH } else { $PSScriptRoot }
    Add-Type -Path (Join-Path $assemblyPath "WinSCPnet.dll")
 
    Add-Type -Assembly PresentationCore
 
    $remotePath = [Windows.Clipboard]::GetText()
    if (!$remotePath)
    {
        throw "No path in clipboard"
    }
 
    # Setup session options
    $sessionOptions = New-Object WinSCP.SessionOptions
    $sessionOptions.ParseUrl($sessionUrl)
 
    $session = New-Object WinSCP.Session
 
    try
    {
        Write-Host "Connecting..."
        # Connect
        $session.Open($sessionOptions)
 
        Write-Host ("Downloading {0}..." -f $remotePath)
        $session.GetFiles($remotePath, $localPath + "\*").Check()
    }
    finally
    {
        # Disconnect, clean up
        $session.Dispose()
    }
 
    Write-Host "Done."
    $result = 0
}
catch [Exception]
{
    Write-Host ("Error: {0}" -f $_.Exception.Message)
    $result = 1
}
 
# Pause if -pause switch was used
if ($pause)
{
    Write-Host "Press any key to exit..."
    [System.Console]::ReadKey() | Out-Null
}
 
exit $result

Advertisement

Options

The Pause at the end makes the script wait for a key press when it finishes.

In the Session log file you can specify a path to a session log file.

Last modified: by martin