Search code examples
powershellsftpremote-serverfilepattern

Delete files with pattern in remote SFTP directory


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


Solution

  • 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)