I found a function online that I modified to better suit my needs. You can see the original here.
I modified the function to allow it to be used non-recursively if so desired. I also had to delete line 25 from the original for it to work properly in Windows 10.
I use this function to find the latest Adobe Reader EXE file available on the Adobe FTP Server.
Function Get-FtpDirectory { [cmdletbinding()] Param ( [parameter(Mandatory=$True,Position=0)][Alias("URL")][string]$Directory, [parameter(Mandatory=$False,Position=1)][Alias("Username")][string]$User = 'anonymous', [parameter(Mandatory=$False,Position=2)][Alias("Password")][string]$Pass = 'anonymous@domain.com', [parameter(Mandatory=$False)][switch]$Recurse = $False ) # Credentials $FTPRequest = [System.Net.FtpWebRequest]::Create($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) $StreamReader.Close() # Close the FTP connection so only one is open at a time $FTPResponse.Close() # 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 -and $Recurse) { # Recursively traverse sub-directories $FileTree += ,(Get-FtpDirectory "$($Directory)$($CurFile)/" -Recurse) } ElseIf ($DirBool) { # Add the output to the file tree $FileTree += ,"$($Directory)$($CurFile)/" } Else { # Add the output to the file tree $FileTree += ,"$($Directory)$($CurFile)" } } Return $FileTree }
Leave a Reply