If you want to try this out, please read this first. There, I did an upload using FTP with network credentials (username and password). This time, I want to show how to download a file using HTTP. I am using PowerShell 2.0.

#Load the System.Net namespace.
("System.Net, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")

#Load the System.IO namespace.
("System.IO, Version=, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")

#The target filename on the local system.
$Target =  "C:\downloaded.wav"

#Full source path.
$RemoteSource = "http://www.mysite.com/myfile.wav"

#Use the static method Create to create a web request.
#Pass the destination as an argument, and cast it to a HttpWebRequest.

#If not anonymous requests are allowed, you can
#add a System.Net.NetworkCredential to the Credentials
#property of the request object ($R).

#What kind of method it will represent? A http request.
$R.Method = "GET"

#Execute and grab the response object (System.Net.WebResponse).
$Resp = $R.GetResponse()

#Get a reference to the response stream (System.IO.Stream).
$RespStream = $Resp.GetResponseStream()

#Create a stream to write to the file system.
$Wrt = [System.IO.File]::Create($Target)

#Create the buffer for copying data.
$Buffer = New-Object Byte[] 1024

#In an iteration...
Do {

#...attemt to read one kilobyte of data from the web response stream.
$BytesRead = $RespStream.Read($Buffer, 0, $Buffer.Length)

#Write the just-read bytes to the target file.
$Wrt.Write($Buffer, 0, $BytesRead)

#Iterate while there's still data on the web response stream.
} While ($BytesRead -gt 0)

#Close the stream.

#Flush and close the writer.

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *