Chapter 12. Internet-Enabled Scripts
12.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.
12.1 Download a File from an FTP or Internet Site
Problem
You want to download a file from an FTP location or website on the internet.
Solution
Use the -OutFile
parameter of the Invoke-WebRequest
cmdlet:
PS > $source = "http://www.leeholmes.com/favicon.ico" PS > $destination = "c:\temp\favicon.ico" PS > PS > Invoke-WebRequest $source -OutFile $destination
Discussion
The Invoke-WebRequest
cmdlet lets you easily upload and download data from remote web servers. It 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.
While the Solution demonstrates downloading a file from a web (HTTP) resource, the Invoke-WebRequest
cmdlet also supports FTP locations. To specify an FTP location, use ftp://
at the beginning of the source, as shown in Example 12-1.
Example 12-1. Downloading a file from an FTP ...
Get PowerShell Cookbook, 4th 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.