1

I'm trying to use FTP to upload a file to an FTP server. I found the following script online, but I can't get it to work.

$UserName = 'username'

$Password = 'password'

$LocalFilePath = 'c:\FolderName\x.txt'

$RemoteFileName = 'x.txt'

$ServerName = 'my.ftpserver.co.uk'


$webclient = New-Object System.Net.WebClient

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

#Connect to FTP
$uri = New-Object System.Uri(“ftp://$ServerName/$RemoteFileName”)
write-host $uri

#upload as file
$webclient.UploadFile($uri, $LocalFilePath)

But when I run this I get the following error:

    Exception calling "UploadFile" with "2" argument(s): "An exception occurred during a WebClient request."
    At line:21 char:22
+ $webclient.UploadFile <<<< ($uri, $LocalFilePath)
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : DotNetMethodException

Can anyone point me in the right direction? I can connect using Filezilla etc from my PC, so it's not blocked by the firewall or anything,

Matt
  • 45,022
  • 8
  • 78
  • 119
IGGt
  • 2,627
  • 10
  • 42
  • 63
  • tested your script, it runs fine... are you using a proxy or something like this? – Avshalom Oct 07 '15 at 09:48
  • Not that I know of, I've tried the connection using various FTP Clients (Filezilla, WinSCP etc) and it works fine. I assumed Powershell would just implement an FTP connection the same as they do, so if they work, powershell should too (or am I wrong?) – IGGt Oct 07 '15 at 10:03
  • Enable [.NET network logging](http://stackoverflow.com/q/9664650/850848) and show us the log. Show us a log from FTP client too (e.g. WinSCP) for comparison. – Martin Prikryl Oct 07 '15 at 13:21
  • Since today i have the same error and can't upload my files anymore. – René Höhle Oct 20 '17 at 21:13

2 Answers2

0

Tested your script and it runs fine, only way I'm able to reproduce your error is if I point $LocalFilePath to a file that doesn't exist. Could you try:

Test-Path($LocalFilePath)

And see if it returns True?

Oggew
  • 366
  • 1
  • 9
  • That returns TRUE. I see to have fixed it though, by changing `New-Object System.Uri(“ftp://$ServerName/$RemoteFileName”)` to `New-Object System.Uri($ftp+$File_Name)` – IGGt Oct 07 '15 at 10:43
0

From your comment and the code I see in the question the issue could just be the fact that you have smart quotes in there. It would be a product of your coding editor or the source of copying and paste that code into your environment. You need to watch out for these things. Assuming the paths are correctly formed perhaps that is just your issue.

Smart Quotes

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

Proper double quotes

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

The quotes in the second example are the ones you should use.

Matt
  • 45,022
  • 8
  • 78
  • 119