Use a PowerShell FTP script to upload and download files

ftp-techtargetSometimes a system administrator needs to get files from point A to point B. And there are many ways to accomplish

this, but one popular method is to use a PowerShell FTP script. Admins can do this by using Windows’ .NET capabilities.

Using PowerShell, Windows admins can use the .NET WebClient class. Let’s create a functional PowerShell FTP script from scratch that can download and upload files. This script will have five essential tasks:

  1. Getting the input
  2. Creating the WebClient object
  3. Creating the Credential object
  4. Creating the Uniform Resource Identifier
  5. Downloading/Uploading the file

The first task is to gather the input from the user. For input data, we’ll include everything needed to use a FTP server through the graphical user interface. This includes username, password, file names and the FTP server name. I’ll assign these as variables so I can easily change them later if needed.

I’ve assigned all of the input data I need into variables. Next, we’ll instantiate a WebClient object.

This command gives us the object to work with that we can use later to upload or download the file.

The WebClient object has a Credentials property, which PowerShell uses to pass the username and password to the FTP server. This Credentials property needs a System.Net.NetworkCredential object that needs two parameters: UserName and Password. We’ll use the username and password we assigned earlier, as such:

 

Decide where to download or upload a file

We now have a WebClient object with the Credentials property populated and must decide where to download or upload a file. Depending on what we choose, the uniform resource identifier (URI) will be different.

For example, if I want to download a file from a remote FTP server, the URI needs to be in the form of ftp://SERVERNAME/filename.ext. We’ll build… Continue reading on SearchWindowsServer.

Adam Bertram

Chief Automator at Adam the Automator, LLC
Adam Bertram is an independent consultant, technical writer, trainer and presenter. Adam specializes in consulting and evangelizing all things IT automation mainly focused around Windows PowerShell. Adam is a Microsoft Windows PowerShell MVP, 2015 powershell.org PowerShell hero and has numerous Microsoft IT pro certifications. He authors IT pro course content for Pluralsight, is a regular contributor to numerous print and online publications and presents at various user groups and conferences.You can find Adam here on the blog or on Twitter at @adbertram.

Latest posts by Adam Bertram (see all)