tags:

views:

1014

answers:

2

I want to use powershell to transfer files with FTP to an anonymous FTP server. I would not use any extra packages. How?

There must be no risk that the script hangs or crashes.

+8  A: 

I am not sure you can 100% bullet proof the script from not hanging or crashing, as there are things outside your control (what if the server loses power mid-upload?) - but this should provide a solid foundation for getting you started:

# create the FtpWebRequest and configure it
$ftp = [System.Net.FtpWebRequest]::Create("ftp://localhost/me.png")
$ftp = [System.Net.FtpWebRequest]$ftp
$ftp.Method = [System.Net.WebRequestMethods+Ftp]::UploadFile
$ftp.Credentials = new-object System.Net.NetworkCredential("anonymous","anonymous@localhost")
$ftp.UseBinary = $true
$ftp.UsePassive = $true
# read in the file to upload as a byte array
$content = gc -en byte c:\me.png
$ftp.ContentLength = $content.Length
# get the request stream, and write the bytes into it
$rs = $ftp.GetRequestStream()
$rs.Write($content, 0, $content.Length)
# be sure to clean up after ourselves
$rs.Close()
$rs.Dispose()
Goyuix
How do I catch errors? What if I can't connect? can't send the file? the connection go down? I want to handle errors and notify the user.
magol
Those are all really good individual questions that pertain to PowerShell scripting in general and can be applied to many more scenarios than just handling ftp transactions. My advice: Browse the PowerShell tag here and read up on error handling. Most of what could go wrong in this script will throw an exception, just wrap the script in something that will handle that.
Goyuix
A: 

There are some other ways too. I have used the following script:

$File = "D:\Dev\somefilename.zip"
$ftp = "ftp://username:[email protected]/pub/incoming/somefilename.zip"

"ftp url: $ftp"

$webclient = New-Object System.Net.WebClient
$uri = New-Object System.Uri($ftp)

"Uploading $File..."

$webclient.UploadFile($uri, $File)

And you could run a script against the windows FTP command line utility using the following command

ftp -s:script.txt (Check out [this article][1])

The following question on SO also answers this: http://stackoverflow.com/questions/936108/how-to-script-ftp-upload-and-download

Cyril Gupta