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

ε祈祈猫儿з 提交于 2020-11-24 19:59:10

问题


I am not experienced with PowerShell and I need help to download several images with similar names from an FTP server. I found a lot in this forum, and I only managed to download one picture. For this I had to enter the name of the file.

I would like to select a date and then download all the pictures with this date and save them in a local folder. I would also like to save the names of the downloaded images in a .txt file

So how can I download the pictures based on the date?

The string 20201009 is the date and the numbers after it are sequential.

I hope you understand what I mean, because it is my first time that I write something in the forum

FTP-Server

$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)

回答1:


If I understand your question correctly, you want to download all files whose name contains "20201009" string, right?

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

It's even easier, if you use 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()

(I'm the author of WinSCP)



来源:https://stackoverflow.com/questions/64754385/download-files-whose-name-contains-a-specific-string-from-an-ftp-server

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!