Bootstrap FreeKB - PowerShell - List files on an FTP server
PowerShell - List files on an FTP server

Updated:   |  PowerShell articles

The following PowerShell script can be used to display the contents of a directory on an FTP server.

# Variables
$FTPServer   = "ftp://example.com/"
$username    = "your FTP server username"
$password    = "your FTP server password"
$directory   = "/path/to/some/directory/on/the/ftp/server"

#Connection String
$credentials = new-object System.Net.NetworkCredential($username, $password)

#Function to view the files in the FTP Server
function View-Files-in-FTP-Server ($url,$credentials) {
    $request = [Net.WebRequest]::Create($url)
    $request.Method = [System.Net.WebRequestMethods+FTP]::ListDirectory
    if ($credentials) { $request.Credentials = $credentials }
    $response = $request.GetResponse()
    $reader = New-Object IO.StreamReader $response.GetResponseStream() 
    $reader.ReadToEnd()
    $reader.Close()
    $response.Close()
}

# Output the content of $directory on the FTP server
$folderPath= $FTPServer + $directory + $folder + "/"
$ListFiles=View-Files-in-FTP-Server -url $folderPath -credentials $credentials
$files = ($ListFiles -split "`r`n")
$files 

 

Here is another example.

$server = "server1.example.com"
$port = "21"
$username = "jane.doe"
$password = "itsasecret"

$ftp = [System.Net.FtpWebRequest]::create("ftp://$server/")
$ftp.Credentials =  New-Object System.Net.NetworkCredential($username,$password)
$ftp.Method = [System.Net.WebRequestMethods+Ftp]::ListDirectoryDetails
$response = $ftp.GetResponse()
$responseStream = $response.GetResponseStream()
$readStream = New-Object System.IO.StreamReader $responseStream
$files = New-Object System.Collections.ArrayList
while ($file = $readStream.ReadLine()) {
  Write-Output $file
}

 




Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter 80ec1f in the box below so that we can be sure you are a human.