Listing files matching wildcard

The following example uses WinSCP .NET assembly from a PowerShell script. If you have another preferred language, you can easily translate it.

Advertisements:

For matching files by a file mask, use the Session.EnumerateRemoteFiles.

For other types of filtering, use the Where-Object cmdlet and for example the -Match operator with a regular expression. Learn about PowerShell comparison operators.

See also Search recursively for text in remote directory / Grep files over SFTP/FTP protocol.

param (
    $remotePath = "/home/user/data/",
    $wildcard = "*.txt"
)
 
try
{
    # Load WinSCP .NET assembly
    Add-Type -Path "WinSCPnet.dll"
 
    # Setup session options
    $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
        Protocol = [WinSCP.Protocol]::Sftp
        HostName = "example.com"
        UserName = "user"
        Password = "mypassword"
        SshHostKeyFingerprint = "ssh-rsa 2048 xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx:xx"
    }
 
    $session = New-Object WinSCP.Session
 
    try
    {
        # Connect
        $session.Open($sessionOptions)
 
        # Get list of matching files in the directory
        $files = $session.EnumerateRemoteFiles($remotePath, $wildcard, [WinSCP.EnumerationOptions]::None)
 
        # Any file matched?
        if ($files.Count -gt 0)
        {
            foreach ($fileInfo in $files)
            {
                Write-Host ("{0} with size {1}, permissions {2} and last modification at {3}" -f
                    $fileInfo.Name, $fileInfo.Length, $fileInfo.FilePermissions, $fileInfo.LastWriteTime)
            }
        }
        else
        {
            Write-Host ("No files matching {0} found" -f $wildcard)
        }
    }
    finally
    {
        # Disconnect, clean up
        $session.Dispose()
    }
 
    exit 0
}
catch [Exception]
{
    Write-Host ("Error: {0}" -f $_.Exception.Message)
    exit 1
}
 
  library_example_listing_files_matching_wildcard.txt · Last modified: by martin
 

Search Documentation

This page

Donate

About donations

$9   $19   $49   $99

About donations

Recommend

Associations

Site design by Black Gate