Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Recursively list all files in FTP directory in PowerShell / List files (recursive)
$Server = ""
$User = ""
$Pass = ""
Function Get-FtpDirectory($Directory) {
# Credentials
$FTPRequest = [System.Net.FtpWebRequest]::Create("$($Server)$($Directory)")
$FTPRequest.Credentials = New-Object System.Net.NetworkCredential($User,$Pass)
$FTPRequest.Method = [System.Net.WebRequestMethods+FTP]::ListDirectoryDetails
# Don't want Binary, Keep Alive unecessary.
$FTPRequest.UseBinary = $False
$FTPRequest.KeepAlive = $False
$FTPResponse = $FTPRequest.GetResponse()
$ResponseStream = $FTPResponse.GetResponseStream()
# Create a nice Array of the detailed directory listing
$StreamReader = New-Object System.IO.Streamreader $ResponseStream
$DirListing = (($StreamReader.ReadToEnd()) -split [Environment]::NewLine)
# Remove first two elements ( . and .. ) and last element (\n)
$DirListing = $DirListing[2..($DirListing.Length-2)]
# Close the FTP connection so only one is open at a time
# This array will hold the final result
$FileTree = @()
# Loop through the listings
foreach ($CurLine in $DirListing) {
# Split line into space separated array
$LineTok = ($CurLine -split '\ +')
# Get the filename (can even contain spaces)
$CurFile = $LineTok[8..($LineTok.Length-1)]
# Figure out if it's a directory. Super hax.
$DirBool = $LineTok[0].StartsWith("d")
# Determine what to do next (file or dir?)
If ($DirBool) {
# Recursively traverse sub-directories
$FileTree += ,(Get-FtpDirectory "$($Directory)$($CurFile)/")
} Else {
# Add the output to the file tree
$FileTree += ,"$($Directory)$($CurFile)"
Return $FileTree

This comment has been minimized.

Copy link

@RitcheS RitcheS commented Feb 17, 2017

Need to add this for an empty directory instead of just line 25

If ($DirListing.Length -gt 3) {
$DirListing = $DirListing[2..($DirListing.Length-2)]
} else {
$DirListing = @{}


This comment has been minimized.

Copy link

@Liturgist Liturgist commented Feb 14, 2018

Does this only work with UNIX-like FTP hosts? Here is what $DirListing looks like from Windows Server 2008 FTP server.

[DBG]: PS C:\src\t\ftp>> $DirListing
02-14-18  04:35PM                    7 a now is the time.txt
02-14-18  04:46PM       <DIR>          aa
01-24-18  06:47AM                  237 HealthFinch_Devl_20180124_0647.7z.001

Also, why are the first and last lines deleted? Is that from . and .. on UNIX-like systems?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.