Delete files with pattern in remote SFTP directory

2k views Asked by At

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

2

There are 2 answers

0
Martin Prikryl On BEST ANSWER

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)

0
Mike Twc On

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.