List Directories

Advertisement

thernandez
Joined:
Posts:
1

List Directories

Is there a way to list all of the directories and files, sub-directories and sub-files within an given ftp folder? The sub-directory could possibly have more directories and more files within it as well. I know there is a Session.ListDirectory() function but this only gets the files\directories of a given folder. I was hoping there was some sort of function as in powershell's function "get-childitem -recurse" which will list everything in a given directory.

Thanks.

Reply with quote

Advertisement

DaPlane
Guest

Quick and dirty way

A bit late, but if it helps, the function below is working for me.

Takes your winscp session as first parameter, and the path you want to recurse.
Returns an object containing your data. You want to enrich this object with additional properties I did not include here...

function Get-WinScpChildItem ($WinScpSession, $BasePath) {

#Get the directory listing
$Directory = $WinScpSession.ListDirectory($BasePath)

#Initialize an empty collection
$MyCollection = @()

#Browse through each entry
foreach ($DirectoryEntry in $Directory.Files) {

#We want to ignore . and .. folders
if (($DirectoryEntry.Name -ne '.') -and ($DirectoryEntry.Name -ne '..')) {

#Initialize an object to which we will add custom properties. You can add all properties you may need later such as Last Write Time etc
        $TempObject = New-Object System.Object

#If the current entry is a directory, we need to add it to our collection, as a directory, then recurse
        if ($DirectoryEntry.IsDirectory) {

#We need to save the BasePath before recursing
            $SavePath = $BasePath

#Special case : Avoid adding an extraneous '/' if we are at the root directory
            if ($BasePath -eq '/') {
                $BasePath += "$($DirectoryEntry.Name)"
                }
            else {
                $BasePath += "/$($DirectoryEntry.Name)"
                }

            $TempObject | Add-Member -MemberType NoteProperty -name 'Name' -Value $BasePath
            $TempObject | Add-Member -MemberType NoteProperty -name 'IsDirectory' -Value $true
            $MyCollection += $TempObject

#Now we recurse, and when done, we reset the BasePath
            $MyCollection += Get-WinScpChildItem $WinScpSession $BasePath
            $BasePath = $SavePath
            }

#If the current entry is a file, it's time to add it to our collection, as a file
        else {
            $TempObject | Add-Member -MemberType NoteProperty -name 'Name' -Value "$BasePath/$DirectoryEntry"
            $TempObject | Add-Member -MemberType NoteProperty -name 'IsDirectory' -Value $false
            $MyCollection += $TempObject
            }
        }
    }

#The function finally returns the collection
return $MyCollection
}

Reply with quote

Advertisement

You can post new topics in this forum