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.

# @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.4
# @option       Pause -config pausecheckbox
# @option       SessionLogPath -config sessionlogfile
# @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
    {
        $session.SessionLogPath = $sessionLogPath
 
        Write-Host "Connecting..."
        # Connect
        $session.Open($sessionOptions)
 
        Write-Host ("Downloading {0}..." -f $remotePath)
        $session.GetFiles($remotePath, (Join-Path $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

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.

 
  library_example_download_clipboard.txt · Last modified: by martin
 

Search Documentation

This page

Donate

About donations

$9   $19   $49   $99

About donations

Recommend

Associations

Site design by Black Gate