Search code examples
powershellftp

Upload files with FTP using PowerShell


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


Solution

  • 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 = [System.IO.File]::ReadAllBytes("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()