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;