powershell: get a web page

Want to grab a web page via PowerShell? Well, I do, and I found a Get-Web function on a MSDN blog post. For me, I tend to manage many web servers and sites using PowerShell scripting, and it might be useful to incorporate some Gets as part of an error checking routine. Or, as in my quick case today, an ugly one-time page monitoring script to look for delivery issues in the wee hours of a morning.

Note: I spent all of 3 minutes searching for this function, so your mileage may vary… The key part to check if you want to roll your own is the “New-Object Net.Webclient” object.

I’ll repost below just in case the source ever disappears from the web, but I suggest copying it from the link above rather than here, due to any formatting issues.

function Get-Web($url,
[switch]$self,
$credential,
$toFile,
[switch]$bytes)
{
#.Synopsis
# Downloads a file from the web
#.Description
# Uses System.Net.Webclient (not the browser) to download data
# from the web.
#.Parameter self
# Uses the default credentials when downloading that page (for downloading intranet pages)
#.Parameter credential
# The credentials to use to download the web data
#.Parameter url
# The page to download (e.g. www.msn.com)
#.Parameter toFile
# The file to save the web data to
#.Parameter bytes
# Download the data as bytes
#.Example
# # Downloads www.live.com and outputs it as a string
# Get-Web http://www.live.com/
#.Example
# # Downloads www.live.com and saves it to a file
# Get-Web http://wwww.msn.com/ -toFile www.msn.com.html
$webclient = New-Object Net.Webclient
if ($credential) {
$webClient.Credential = $credential
}
if ($self) {
$webClient.UseDefaultCredentials = $true
}
if ($toFile) {
if (-not “$toFile”.Contains(“:”)) {
$toFile = Join-Path $pwd $toFile
}
$webClient.DownloadFile($url, $toFile)
} else {
if ($bytes) {
$webClient.DownloadData($url)
} else {
$webClient.DownloadString($url)
}
}
}