Chapter 12. Internet-Enabled Scripts
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.
Download a File from the Internet
Problem
You want to download a file from a website 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, 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 ...
Get Windows PowerShell Cookbook, 2nd Edition 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.