HeadShot September 2014.jpg

Kieran Jacobsen is the Head of Information Technology at Readify, a Microsoft MVP and regular speaker at conferences throughout Australia.

Accessing the Internet from PowerShell: Download Files Part 2

So, last time we looked at download a file, and looked at what a CMDLet to do this should look like.

And here it is:


Most of the layout of this CMDLet should be familiar to you. There is the comment based help, then the CMDLetBinding. We then have a list of parameters, URL is the only one which is mandatory, and the others are all optional. URL is also set to accept the value from the pipeline, this is the first step to meeting the first requirement of our CMDLet. The filename and directory parameters are for specifying the intended destination files name and location. Finally clobber is a switch, meaning it is either on or off. Clobber will be the way the user of the CMDLet tells it to overwrite files.

Next you will notice a Begin {} block of code. In here we are going to be creating the WebClient object and setting all of its options. Begin{} blocks will only get executed once, no matter how many items are passed in on the pipeline. Begin{} will occur before any input data is processed. End{} which isn’t used, is only executed once all the processing is completed.

A Process{} block is next. Process{} will be executed for every item passed in on the pipeline to the CMDLet. In this block we spend time working out the destination filename and path, then we will test to see if it exists. If the file already exists, then we can either, raise a warning that we are overwriting the file, or throw an error. This will be determined by the clobber parameter.

Finally we are going to write the full url and destination path to verbose output and download the file. We will throw any errors encountered back to the calling code.

Let’s look at how to use the cmdlet:

So, now you have it. You can download files.

PowerShell Malware

Accessing the Internet from PowerShell: Download Files Part 1