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 ("$($fileInfo.Name) with size $($fileInfo.Length), " +
                    "permissions $($fileInfo.FilePermissions) and " +
                    "last modification at $($fileInfo.LastWriteTime)")
            }
        }
        else
        {
            Write-Host "No files matching $wildcard found"
        }
    }
    finally
    {
        # Disconnect, clean up
        $session.Dispose()
    }
 
    exit 0
}
catch
{
    Write-Host "Error: $($_.Exception.Message)"
    exit 1
}
 
  library_example_listing_files_matching_wildcard.txt · Last modified: by martin
 

Search

This page

Donate

About donations

$9   $19   $49   $99

About donations

Recommend

Associations

Site design by Black Gate