1

I need to delete files matching some pattern (name containing a specific string) from a remote directory on an SFTP server using PS.

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
ITE
  • 67
  • 7

2 Answers2

4

There's no native support for SFTP in PowerShell. You have to use a 3rd party SFTP library.

For example with WinSCP .NET assembly, you can do this:

Add-Type -Path "WinSCPnet.dll"

$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
    Protocol = [WinSCP.Protocol]::Sftp
    HostName = "example.com"
    UserName = "username"
    Password = "password"
    SshHostKeyFingerprint = "ssh-rsa 2048 ..."
}

$session = New-Object WinSCP.Session

$session.Open($sessionOptions)

$session.RemoveFiles("/remote/path/*string*").Check()

$session.Dispose()

WinSCP GUI can generate code template for you.

(I'm the author of WinSCP)

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
1

You can also try ssh.net library (it's pretty lightweight)
https://github.com/sshnet/SSH.NET After you build it the base syntax will look like this

Add-Type -Path "path\to\Renci.SshNet.dll"
$conn = New-Object Renci.SshNet.SftpClient -ArgumentList @($HostName, $PortNumber, $UserName, $Password)
$conn.connect()
$files = $conn.ListDirectory("DirName").FullName | where { $_ -like "*.csv"}
$files | foreach { $conn.Delete($_) }

You can also install GitBash, then you'll have ssh command available in your terminal.

Mike Twc
  • 2,230
  • 2
  • 14
  • 19