Search code examples
powershellftpftpwebrequestsplit

How to count files in FTP directory


I have this script. I'm trying to count how many file are in.

clear
$ftp_uri = "ftp://ftp.domain.net:"
$user = "username"
$pass = "password"
$subfolder = "/test/out/"
$ftp_urix = $ftp_uri + $subfolder
$uri=[system.URI] $ftp_urix

$ftp=[system.net.ftpwebrequest]::Create($uri)

$ftp.Credentials=New-Object System.Net.NetworkCredential($user,$pass)

#Get a list of files in the current directory.
$ftp.Method=[system.net.WebRequestMethods+ftp]::ListDirectorydetails
$ftp.UseBinary = $true
$ftp.KeepAlive = $false
$ftp.EnableSsl = $true
$ftp.Timeout = 30000
$ftp.UsePassive=$true

try
{
 $ftpresponse=$ftp.GetResponse()
 $strm=$ftpresponse.GetResponseStream()
 $ftpreader=New-Object System.IO.StreamReader($strm,'UTF-8')
 $list=$ftpreader.ReadToEnd()

 $lines=$list.Split("`n")

 $lines
 $lines.Count

 $ftpReader.Close() 
 $ftpresponse.Close()
}
catch{
 $_|fl * -Force
 $ftpReader.Close() 
 $ftpresponse.Close()
}

In the directory I have three files but $lines.count return 4. $lines have 4 rows, three files and an empty line. Somebody can explain me the mystery?


Solution

  • The $list contains:

    file1`nfile2`nfile3`n
    

    If you split the string by "`n", you (correctly) get four parts, with the last one being empty.

    You can use an overload of String.Split that takes StringSplitOptions and use RemoveEmptyEntries:

    $list.Split("`n", [System.StringSplitOptions]::RemoveEmptyEntries)