0

Hello everybody I've been strugglling for many days now with this, I would like to get some help. What I am trying to do is to download the latest files from FTP server but what I've got here is going to download all the files from the ftp server !!! I don't know how to add condition in a powershell script I'm a newbie to this. Gonna drop what I have for now just here.

So please let me know if any additional information is required and I will provide it immediately, thanks again for your help.

`Write-Host "Please wait while your file downloads"

  #Function to get all files
  function Get-FtpDir ($url,$credentials)
  {
   $request = [Net.WebRequest]::Create($url)
   $request.Credentials = $credentials
   $request.Method = [System.Net.WebRequestMethods+FTP]::ListDirectory
   $response = $request.GetResponse()
   $reader = New-Object IO.StreamReader $response.GetResponseStream()
   $readline = $reader.ReadLine()
   $output = New-Object System.Collections.Generic.List[System.Object]
   while ($readline -ne $null)
   {
      $output.Add($readline)
      $readline = $reader.ReadLine()
   }
  $reader.Close()
  $response.Close()
  $output
  }

 $server = 'ftp.xxxx.xxx'
 $user = 'xxxxx'
 $pass = 'xxxxxxxxx'

 $localfilelocation = 'C:\Users\Lala\Desktop\test\'
 $uri = New-Object System.Uri("ftp://$server/")

#List of all files on FTP-Server
$files = Get-FTPDir $uri -credentials (New-Object System.Net.NetworkCredential($user,     $pass))

 foreach ($file in $files)
 {
  if ($file)
  {
     $file
     $path = "$localfilelocation\$file"
     $fileuri = New-Object System.Uri("ftp://$server/$file")
     $webclient = New-Object System.Net.WebClient
     $webclient.Credentials = New-Object System.Net.NetworkCredential($user, $pass)
     $webclient.DownloadFile($fileuri,$path )
 }

}

Cloud
  • 1
  • 1
  • @MartinPrikryl thank you for your answer but I can't use WinSCP and that's why I wanted to know if it's possible to do so without WinSCP ? I mean just a powershell script, the issue I have is that i don't know how to put in my conditions to get to files.. – Cloud Jul 28 '21 at 11:15
  • 1) Your question does not mention any such constraint. 2) The first part of my answer sketches the solution needed for pure .NET solution. Your current code is miles away from that. If you hoped for an easy solution without using 3rd party library/tool – there's none. – Martin Prikryl Jul 28 '21 at 11:18
  • You are right I didn't mention any of that but I still can't use it. My current code does work, it does download the files but all of them and that's not what I need. Well at least I know there's no solutions using only powershell. Thanks again – Cloud Jul 28 '21 at 11:31
  • Where did I wrote that there's *no solution*? I wrote that's there's no *easy solution*. But of course that it is possible. It's just lot of work. All the code that you need is linked in my answer to the duplicate question. – Martin Prikryl Jul 28 '21 at 11:36

0 Answers0