Reputation: 300
I am working on a FTP automation script that will upload certain files from a network share to a specific location on a FTP server. I found the below, but am unable to edit it to navigate to the desired destination directory.
#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)
}
I have credentials to the FTP server but am defaulted to /home/MyUser/
and I need to direct to /home/OtherUser/
. I do have permissions to browse to and upload to that directory, but I can't figure out how to, essentially, cd to that location.
Here is the current error received:
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
Upvotes: 1
Views: 2268
Reputation:
You need to use the FtpWebRequest
type. The WebClient
is used for HTTP traffic.
I have written and tested a parameterized function that will upload a file to a FTP server, called Send-FtpFile
. I used the sample C# code from MSDN to translate this into PowerShell code, and it works quite well.
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;
Upvotes: 2