如何计算 FTP 目录中的文件

How to count files in FTP directory

我有这个脚本。我正在计算有多少文件。

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()
}

在目录中我有三个文件但是 $lines.count return 4. $lines 有 4 行,三个文件和一个空行。谁能给我解开谜底?

$list 包含:

file1`nfile2`nfile3`n

如果用“`n”分割字符串,您(正确地)得到四个部分,最后一个为空。

您可以使用 overload of String.Split that takes StringSplitOptions 并使用 RemoveEmptyEntries:

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