我有以下代码通过powershell将文件上传到FTP服务器,但这给了我这个错误:
代码:
$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
答案 0 :(得分:0)
尝试一下:
$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)
}
区别在于,我正在使System.Uri结合路径而不是依赖于字符串连接,并且我告诉WebClient.UploadFile()上载文件时要使用的方法。
如果这不起作用,那么我同意您应该检查服务器日志的评论。如果不能,请在可以查看其日志的服务器上尝试。或者,您可能想尝试使用WinSCP,它也可以通过PowerShell或自定义脚本文件编写脚本。 WinSCP还具有支持FTP,FTPS和SFTP的优势。据我所知,.Net WebClient仅本地支持纯FTP。
就智能引号而言,它们在Windows PowerShell(<= v5.x)上可以正常工作,但在PowerShell Core(v6 +)上却根本不起作用。我会避免使用它们来使您的代码更具可移植性,并为将来提供更多证明。