Chapter 9. Internet-Enabled Scripts

9.0. Introduction

Although PowerShell provides an enormous benefit even when your scripts interact only with the local system, working with data sources from the Internet opens exciting and unique opportunities. For example, you might download files or information from the Internet, interact with a web service, store your output as HTML, or even send an email that reports the results of a long-running script.

Through its cmdlets and access to the networking support in the .NET Framework, PowerShell provides ample opportunities for Internet-enabled administration.

9.1. Download a File from the Internet

Problem

You want to download a file from a web site on the Internet.

Solution

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)

Discussion

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, 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 web site what application is making the request—such as Internet Explorer, Firefox, or an automated crawler from ...

Get Windows PowerShell Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.