【问题标题】:How to count files in FTP directory如何统计FTP目录中的文件
【发布时间】:2015-06-01 07:20:51
【问题描述】:

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

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 返回 4。$lines 有 4 行,三个文件和一个空行。谁能给我解释一下其中的奥秘?

【问题讨论】:

    标签: powershell ftp ftpwebrequest string-split


    【解决方案1】:

    $list 包含:

    file1`nfile2`nfile3`n
    

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

    您可以使用带有StringSplitOptionsoverload of String.Split 并使用RemoveEmptyEntries

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

    【讨论】:

      猜你喜欢
      • 2019-09-12
      • 1970-01-01
      • 2011-03-11
      • 1970-01-01
      • 2019-11-13
      • 1970-01-01
      • 2023-03-10
      • 1970-01-01
      • 2011-11-07
      相关资源
      最近更新 更多