Jump to content

How to Download a File from the Internet with Windows PowerShell

0
  chco's Photo
Posted Sep 01 2010 08:10 AM

If you want to download a file from a website on the Internet using Windows PowerShell then this excerpt from Windows PowerShell Cookbook, Second Edition can be of help.
Use the DownloadFile() method from the .NET Framework's System.Net.WebClient class to download a file:

PS > $source = "http://www.leeholmes.com/favicon.ico"
PS > $destination = "c:\temp\favicon.ico"
PS >
PS > $wc = New-Object System.Net.WebClient
PS > $wc.DownloadFile($source, $destination)


The System.Net.WebClient class from the .NET Framework lets you easily upload and download data from remote web servers.

The WebClient class acts much like a web browser, in that you can specify a user agent, a proxy (if your outgoing connection requires one), and even credentials.

All web browsers send a user agent identifier along with their web request. This identifier tells the website what application is making the request—such as Internet Explorer, Firefox, or an automated crawler from a search engine. Many websites check this user agent identifier to determine how to display the page. Unfortunately, many fail entirely if they can’t determine the user agent for the incoming request. To make the System.Net.WebClient identify itself as Internet Explorer, use the following commands instead:

$userAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2;)"
$wc = New-Object System.Net.WebClient
$wc.Headers.Add("user-agent", $userAgent)


Notice that the solution uses a fully qualified path for the destination file. This is an important step, as otherwise the DownloadFile() method saves its files to the directory in which PowerShell.exe started (the root of your user profile directory by default).

You can use the DownloadFile() method to download web pages just as easily as you download files. Just supply a URL as a source (such as http://blogs.msdn.co...ershell/rss.xml) instead of a filename. If you ultimately intend to parse or read through the downloaded page, the DownloadString() method may be more appropriate.

Cover of Windows PowerShell Cookbook
Learn more about this topic from Windows PowerShell Cookbook, 2nd Edition. 

This introduction to the Windows PowerShell language and scripting environment provides more than 430 task-oriented recipes to help you solve the most complex and pressing problems, and includes more than 100 tried-and-tested scripts that intermediate to advanced system administrators can copy and use immediately. You'll find hands-on tutorials on fundamentals, common tasks, and administrative jobs that you can apply whether you're on a client or server version of Windows.

Learn More Read Now on Safari


Tags:
0 Subscribe


0 Replies