Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function SFTP-Download {
- [cmdletbinding()]
- param(
- [Parameter(Mandatory=$true)]
- [string]$sitehost,
- [Parameter(Mandatory=$true)]
- [string]$port,
- [Parameter(Mandatory=$true)]
- [string]$user,
- [Parameter(Mandatory=$true)]
- [string]$pass,
- [Parameter(Mandatory=$true)]
- [string]$local,
- [Parameter(Mandatory=$true)]
- [string]$remote,
- [Parameter(Mandatory=$true)]
- $winscpdll,
- [Parameter(Mandatory=$true)]
- [string]$sshkey
- )
- process{
- # Load WinSCP .NET assembly
- Add-Type -Path $winscpdll
- # Setup session options
- $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
- Protocol = [WinSCP.Protocol]::Sftp
- PortNumber = "$port"
- HostName = "$sitehost"
- UserName = "$user"
- Password = "$pass"
- SshHostKeyFingerprint = "$sshkey"
- }
- # Create Session
- $session = New-Object WinSCP.Session
- # Connect
- $session.Open($sessionOptions)
- # Find files and count
- $remotefiles = $session.EnumerateRemoteFiles($remote, "*.txt", [WinSCP.EnumerationOptions]::None)
- $remotefilescount = ($remotefiles.count).count
- if ($remotefilescount -gt 0) {
- Write-Host "$remotefilescount Files found" -ForegroundColor Green
- # Download the file and throw on any error
- $downloadresult = $session.GetFiles(($remote),($local))
- foreach ($download in $downloadresult) {
- if ($download.IsSuccess) {
- Write-Host "$($download.error)"
- }
- else {
- Write-Host "$download download was not successful"
- }
- }
- # Remove file
- #$removeresult = $session.RemoveFiles($remote)
- #if ($removeresult.IsSuccess) {
- #Write-Host "The files were removed!"
- #}
- #else {
- #Write-Host "There was an issue removing"
- #}
- # Disconnect session
- $session.dispose()
- }
- else {
- Write-Host "There were no files found!" -ForegroundColor Red
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement