我正在开发一个FTP自动化脚本,它将某些文件从网络共享上传到FTP服务器上的特定位置。我找到了下面的内容,但无法编辑它以导航到所需的目标目录。
#ftp server
$ftp = "ftp://SERVER/OtherUser/"
$user = "MyUser"
$pass = "MyPass"
$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)
#list every sql server trace file
foreach($item in (dir $Dir "*.trc")){
"Uploading $item..."
$uri = New-Object System.Uri($ftp+$item.Name)
$webclient.UploadFile($uri, $item.FullName)
}
我有FTP服务器的凭据,但默认为/home/MyUser/
,我需要直接转到/home/OtherUser/
。我有权浏览并上传到该目录,但我无法弄清楚如何基本上cd到该位置。
以下是收到的当前错误:
Exception calling "UploadFile" with "2" argument(s): "The remote server returned an erro
r: (550) File unavailable (e.g., file not found, no access)."
At line:26 char:26
+ $webclient.UploadFile <<<< ($uri, $item.FullName)
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
答案 0 :(得分:2)
您需要使用FtpWebRequest
类型。 WebClient
用于HTTP流量。
我编写并测试了一个参数化函数,该函数将文件上传到名为Send-FtpFile
的FTP服务器。我使用sample C# code from MSDN将其转换为PowerShell代码,并且效果很好。
function Send-FtpFile {
[CmdletBinding()]
param (
[ValidateScript({ Test-Path -Path $_; })]
[string] $Path
, [string] $Destination
, [string] $Username
, [string] $Password
)
$Credential = New-Object -TypeName System.Net.NetworkCredential -ArgumentList $Username,$Password;
# Create the FTP request and upload the file
$FtpRequest = [System.Net.FtpWebRequest][System.Net.WebRequest]::Create($Destination);
$FtpRequest.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile;
$FtpRequest.Credentials = $Credential;
# Get the request stream, and write the file bytes to the stream
$RequestStream = $FtpRequest.GetRequestStream();
Get-Content -Path $Path -Encoding Byte | % { $RequestStream.WriteByte($_); };
$RequestStream.Close();
# Get the FTP response
[System.Net.FtpWebResponse]$FtpRequest.GetResponse();
}
Send-FtpFile -Path 'C:\Users\Trevor\Downloads\asdf.jpg' `
-Destination 'ftp://google.com/folder/asdf.jpg' `
-Username MyUsername -Password MyPassword;