Differences
This shows you the differences between the selected revisions of the page.
2013-05-23 | 2013-05-23 | ||
c# + vb.net examples (martin) | powershell example (martin) | ||
Line 158: | Line 158: | ||
Private Shared _lastFileName As String | Private Shared _lastFileName As String | ||
End Class | End Class | ||
+ | </code> | ||
+ | |||
+ | ==== [[powershell]] PowerShell Example ==== | ||
+ | Learn more about [[library_powershell|using WinSCP .NET assembly from PowerShell]]. | ||
+ | |||
+ | &beta (* .dll *) | ||
+ | <code powershell> | ||
+ | # Load WinSCP .NET assembly | ||
+ | # Use "winscp.dll" for the releases before the latest beta version. | ||
+ | [Reflection.Assembly]::LoadFrom("WinSCPnet.dll") | Out-Null | ||
+ | |||
+ | # Session.FileTransferProgress event handler | ||
+ | |||
+ | function FileTransferProgress | ||
+ | { | ||
+ | Param($e) | ||
+ | |||
+ | # New line for every new file | ||
+ | if (($script:lastFileName -ne $Null) -and | ||
+ | ($script:lastFileName -ne $e.FileName)) | ||
+ | { | ||
+ | Write-Host | ||
+ | } | ||
+ | |||
+ | # Print transfer progress | ||
+ | Write-Host -NoNewline ("`r{0} ({1:P0})" -f $e.FileName, $e.FileProgress) | ||
+ | |||
+ | # Remember a name of the last file reported | ||
+ | $script:lastFileName = $e.FileName | ||
+ | } | ||
+ | |||
+ | # Main script | ||
+ | |||
+ | $script:lastFileName = $Null | ||
+ | |||
+ | try | ||
+ | { | ||
+ | $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 | ||
+ | { | ||
+ | # Will continuously report progress of transfer | ||
+ | $session.add_FileTransferProgress( { FileTransferProgress($_) } ) | ||
+ | |||
+ | # Connect | ||
+ | $session.Open($sessionOptions) | ||
+ | |||
+ | # Download the file and throw on any error | ||
+ | $session.GetFiles("/home/martin/public_html/", "d:\backup\").Check() | ||
+ | } | ||
+ | finally | ||
+ | { | ||
+ | # Terminate line after the last file (if any) | ||
+ | if ($script:lastFileName -ne $Null) | ||
+ | { | ||
+ | Write-Host | ||
+ | } | ||
+ | |||
+ | # Disconnect, clean up | ||
+ | $session.Dispose() | ||
+ | } | ||
+ | |||
+ | exit 0 | ||
+ | } | ||
+ | catch [Exception] | ||
+ | { | ||
+ | Write-Host $_.Exception.Message | ||
+ | exit 1 | ||
+ | } | ||
</code> | </code> |