从 FTP 服务器下载名称包含特定字符串的文件

Download files whose name contains a specific string from an FTP server

我没有使用 PowerShell 的经验,我需要帮助才能从 FTP 服务器下载多个名称相似的图像。我在这个论坛里找了很多,我只下载了一张图片。为此,我必须输入文件名。

我想select一个日期,然后下载这个日期的所有图片并保存在本地文件夹中。 我也想把下载的图片的名称保存在.txt文件中

那么如何根据日期下载图片呢?

字符串20201009是日期,后面的数字是连续的

希望大家明白我的意思,因为我是第一次在论坛写东西

$UserName = "abc"
$Password = "abc"

$RemoteFileName =  "DatenTestKam3_schlecht_20201009_085248_00848.jpg"
$LocalFilePath = "C:\Users\Desktop\PowerShell$RemoteFileName"

$ServerName = "10.196.195.167/22_test"

$webclient = New-Object System.Net.WebClient

$webclient.Credentials = New-Object System.Net.NetworkCredential($UserName, $Password)

$uri = New-Object System.Uri(“ftp://$ServerName/$RemoteFileName”)

$webclient.DownloadFile($uri, $LocalFilePath)

如果我没看错你的问题,你想下载名称中包含“20201009”字符串的所有文件,对吧?

$url = "ftp://ftp.example.com/remote/path/"
$credentials = New-Object System.Net.NetworkCredential("username", "password")
$request = [System.Net.WebRequest]::Create($url)
$request.Credentials = $credentials
$request.Method = [System.Net.WebRequestMethods+Ftp]::ListDirectory
$response = $request.GetResponse()
$reader = New-Object IO.StreamReader $response.GetResponseStream() 
$listing = $reader.ReadToEnd()
$reader.Close()
$response.Close()

$localpath = "C:\Users\Desktop\PowerShell"
$date = "20201009"
$files =
    ($listing -split "`r`n") |
    Where-Object {$_ -like "*$date*"}

$webclient = New-Object System.Net.WebClient 
$webclient.Credentials = $credentials

foreach ($file in $files)
{
    $localfilepath = (Join-Path $localPath $file)
    Write-Host ($file + " => " + $localfilepath)

    $webclient.DownloadFile(($url + $file), $localfilepath)
}

如果你使用 WinSCP .NET assembly:

就更简单了
Add-Type -Path "WinSCPnet.dll"

$sessionOptions = New-Object WinSCP.SessionOptions -Property @{
    Protocol = [WinSCP.Protocol]::Ftp
    HostName = "ftp.example.com"
    UserName = "username"
    Password = "password"
}

$session = New-Object WinSCP.Session

$session.Open($sessionOptions)

$localpath = "C:\Users\Desktop\PowerShell"
$date = "20201009"
$session.GetFilesToDirectory("/remote/path", $localpath, "*$date*").Check()

$session.Dispose()

(我是WinSCP的作者)