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.

You can install this script as an 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 -STA -File "%EXTENSION_PATH%" ^
#                   -sessionUrl "!E" -localPath "!\" %Pause% -sessionLogPath "%SessionLogPath%"
# @description  Downloads remote file from a path stored in clipboard ^
#                   to the current local directory
# @version      6
# @homepage     https://winscp.net/eng/docs/library_example_download_clipboard
# @require      WinSCP 5.16
# @option       Pause -config pausecheckbox
# @option       SessionLogPath -config sessionlogfile
# @optionspage  https://winscp.net/eng/docs/library_example_download_clipboard#options
 
param (
    # Use Generate Session URL function to obtain a value for -sessionUrl parameter.
    $sessionUrl = "sftp://user:mypassword;fingerprint=ssh-rsa-xxxxxxxxxxx...@example.com/",
    [Parameter(Mandatory = $True)]
    $localPath,
    $sessionLogPath = $Null,
    [Switch]
    $pause
)
 
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
    {
        $session.SessionLogPath = $sessionLogPath
 
        Write-Host "Connecting..."
        # Connect
        $session.Open($sessionOptions)
 
        Write-Host "Downloading $remotePath..."
        $session.GetFiles($remotePath, (Join-Path $localPath "*")).Check()
    }
    finally
    {
        # Disconnect, clean up
        $session.Dispose()
    }
 
    Write-Host "Done."
    $result = 0
}
catch
{
    Write-Host "Error: $($_.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.

In the Keyboard shortcut, you can specify a keyboard shortcut for the extension.

Last modified: by martin