I am trying to download all files located within a specific folder on a FTP site. The folder is called "In"
(as shown in example code) and contains a number of .txt files.
When I run the below code it lists the four .txt files located in the FTP folder "ftp3.example.com/Jaz/In/"
, however it does not copy them to the target folder of "C:\Users\Jasdeep\Destination\"
Note: The list appears for a split second and then PowerShell closes.
Please see screenshot which shows output list
I have granted full permissions to the folders and contents on FTP Site.
Could someone please advise where I am going wrong?
$ftp = "ftp://ftp3.example.com/Jaz/In/"
$user = 'username'
$pass = 'password'
$folder = "/"
$target = 'C:\Users\Jasdeep\Destination'
$credentials = new-object System.Net.NetworkCredential($user, $pass)
function Get-FtpDir ($url,$credentials) {
$request = [Net.WebRequest]::Create($url)
$request.Method = [System.Net.WebRequestMethods+FTP]::ListDirectory
if ($credentials) { $request.Credentials = $credentials }
$response = $request.GetResponse()
$reader = New-Object IO.StreamReader $response.GetResponseStream()
$reader.ReadToEnd()
$reader.Close()
$response.Close()
}
$folderPath= $ftp + "/" + $folder + "/"
$Allfiles=Get-FTPDir -url $folderPath -credentials $credentials
$files = ($Allfiles -split "`r`n")
$files
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)
$counter = 0
foreach ($file in ($files | where {$_ -like "*.*"})){
$source=$folderPath + $file
$destination = $target + $file
$webclient.DownloadFile($source, (Join-Path $target $file))
$counter++
$counter
$source
}
Thank you in advance!