DownloadSFTPFileCmdlet.cs
using Renci.SshNet;
using System; using System.Collections.Generic; using System.Management.Automation; using System.Text; namespace SFTPSyncer { [Cmdlet("Download", "SFTPFile")] public class DownloadSFTPFileCmdlet : Cmdlet { [Parameter(Position = 0, Mandatory = true)] [ValidateNotNullOrEmpty()] public SftpClient Connection { get; set; } [Parameter(Position = 1, Mandatory = true)] public string Filename { get; set; } [Parameter(Position = 2, Mandatory = true)] public string Target { get; set; } protected override void ProcessRecord() { base.ProcessRecord(); System.IO.Stream targetStream = null; try { if (System.IO.File.GetAttributes(Target).HasFlag(System.IO.FileAttributes.Directory)) { var fn = System.IO.Path.GetFileName(Filename); var targetFile = System.IO.Path.Combine(Target, fn); targetStream = System.IO.File.Create(targetFile); } else { targetStream = System.IO.File.Create(Target); } Connection.DownloadFile(Filename, targetStream); } finally { targetStream?.Dispose(); } } } } |