简体   繁体   中英

Upload files to an FTP Server using powershell

I have the following code to upload a file to an FTP Server via powershell but it's giving me this error:



$Directory=”C:\test”

#FTP server configuration
$ftpserver = “ftp://ftpserver/”
$username = “user”
$password = “pw”

$webclient = New-Object System.Net.WebClient

$webclient.Credentials = New-Object System.Net.NetworkCredential($username,$password)

#Copy each file which type is *.tx*
foreach($file in (dir $Directory “*.txt*”)){
“Uploading $file…”
$uri = New-Object System.Uri($ftpserver+$file.Name)
$webclient.UploadFile($uri, $file.FullName)
}

Exception calling "UploadFile" with "2" argument(s): "Excepção durante um pedido WebClient."
At C:\Users\home\Desktop\test6.ps1:16 char:1
+ $webclient.UploadFile($uri, $file.FullName)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : WebException

Try it like so:

$Directory = "C:\test"

#FTP server configuration
$ftpserver = "ftp://ftpserver/"
$username = "user"
$password = "pw"
$ftpserverURI = New-Object -TypeName System.Uri -ArgumentList $ftpserver, [System.UriKind]::Absolute

$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object -TypeName System.Net.NetworkCredential -ArgumentList $username, $password

#Copy each file which type is *.tx*
Get-ChildItem $Directory -Filter *.txt* | ForEach-Object {
    Write-Host "Uploading $($_.FullName)..."
    $uri = New-Object -TypeName System.Uri -ArgumentList $ftpserverURI, $_.Name
    $webclient.UploadFile($uri, [System.Net.WebRequestMethods+Ftp]::UploadFile, $_.FullName)
}

The differences are that I'm making System.Uri combine the path instead of relying on string concatenation, and I'm telling WebClient.UploadFile() the method to use when uploading the file.

If this doesn't work, then I agree with the comments that you should examine the server logs. If you can't, then try it against a server that you can see the logs for. Alternately, you may want to try to use WinSCP, which is also scriptable with PowerShell or with a custom script file. WinSCP has the advantage of supporting FTP, FTPS, and SFTP, as well. The .Net WebClient only natively supports plain FTP, as far as I'm aware.

As far as smart quotes, they work just fine on Windows PowerShell (<= v5.x), but they don't work at all on PowerShell Core (v6+). I would avoid using them to make your code more portable and more future proof.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM